替换字符串列表中的函数

时间:2018-09-11 23:38:18

标签: python string python-3.x list list-comprehension

我想遍历字符串列表,并用一个单词替换每个字符实例(例如“ 1”)。我很困惑为什么这行不通。

for x in list_of_strings:
    x.replace('1', 'Ace')

请注意,列表中的字符串长度为多个字符。 (黑桃'1)

1 个答案:

答案 0 :(得分:4)

您可以使用列表理解:

list_of_strings = [x.replace('1', 'Ace') for x in list_of_strings]

这在Python中很自然。直接更改原始列表没有明显的好处;两种方法的时间复杂度均为O( n )。

您的代码无效的原因是str.replace不能正常运行。它返回一个副本,如mentioned in the docs。您可以 遍历range对象来修改列表:

for i in range(len(list_of_strings)):
    list_of_strings[i] = list_of_strings[i].replace('1', 'Ace')

或使用enumerate

for idx, value in enumerate(list_of_strings):
    list_of_strings[idx] = value.replace('1', 'Ace')
相关问题