Patrick S
Patrick S

Reputation: 57

Replace function in list of strings

I would like to iterate through a list of strings and replace each instance of a character ('1', for example) with a word. I am confused why this would not work.

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

Side note, the strings within the lists are multiple characters long. ('1 of Spades)

Upvotes: 2

Views: 80

Answers (1)

jpp
jpp

Reputation: 164673

You can use a list comprehension:

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

This is natural in Python. There is no significant benefit in changing your original list directly; both methods will have O(n) time complexity.

The reason your code does not work is str.replace does not work in place. It returns a copy, as mentioned in the docs. You can iterate over a range object to modify your list:

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

Or use enumerate:

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

Upvotes: 4

Related Questions