How to Replace a String in a list in Python

To replace a string in a list, loop through each item in the list and replace the value using the Python .replace() function then append each string to a new list.

 

Let's try this out with an example:

 

items = ['a', 'b', 'c']

new_items = []

for i in items:
   new_items.append(i.replace('b', 'thing'))
   
print(new_items)
['a', 'thing', 'c']

 

It is important to be aware that any occurrence of the string will be replaced whether it is the full string or a substring. You can see this behaviour in the example below:

 

items = ['ab', 'b', 'c']

new_items = []

for i in items:
   new_items.append(i.replace('b', 'thing'))
   
print(new_items)
['athing', 'thing', 'c']
list string

Related Tutorials

 thumbnail

Python Print Formatting

September 24, 2020