我有一个类似的字符串列表:
example = [["string 1", "a\r\ntest string:"],["string 1", "test 2: another\r\ntest string"]]
I'd like to replace the "\r\n"
with a space (and strip off the ":"
at the end for all the strings).
对于普通列表,我将使用列表理解来剥离或替换类似
example = [x.replace('\r\n','') for x in example]
甚至lambda函数
map(lambda x: str.replace(x, '\r\n', ''),example)
但我无法将其用于嵌套列表。有什么建议么?
下面的示例在列表(子列表)列表之间进行迭代,以替换字符串,单词。
如果您的列表比示例中的列表复杂,例如,如果它们具有三层嵌套,则以下内容将遍历该列表及其所有子列表,用任何字符串中的空格替换\ r \ n它碰到了。
好吧,考虑一下原始代码在做什么:
You're using the
.replace()
method on each element of the list as though it were a string. But each element of this list is another list! You don't want to call.replace()
on the child list, you want to call it on each of its contents.对于嵌套列表,请使用嵌套列表推导!