2

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)

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

1 Comment

In-place version would look nicer with enumerate, in my opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.