Find and replace string values in list


Question

I got this list:

words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really']

What I would like is to replace [br] with some fantastic value similar to <br /> and thus getting a new list:

words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really']
1
128
4/20/2019 4:46:17 PM

Accepted Answer

words = [w.replace('[br]', '<br />') for w in words]

These are called List Comprehensions.

225
8/27/2019 12:55:06 PM

Beside list comprehension, you can try map

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon