Find and replace string values in list

PythonStringList

Python Problem Overview


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']

Python Solutions


Solution 1 - Python

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

These are called List Comprehensions.

Solution 2 - Python

You can use, for example:

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

Solution 3 - Python

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']

Solution 4 - Python

In case you're wondering about the performance of the different approaches, here are some timings:

In [1]: words = [str(i) for i in range(10000)]

In [2]: %timeit replaced = [w.replace('1', '<1>') for w in words]
100 loops, best of 3: 2.98 ms per loop

In [3]: %timeit replaced = map(lambda x: str.replace(x, '1', '<1>'), words)
100 loops, best of 3: 5.09 ms per loop

In [4]: %timeit replaced = map(lambda x: x.replace('1', '<1>'), words)
100 loops, best of 3: 4.39 ms per loop

In [5]: import re

In [6]: r = re.compile('1')

In [7]: %timeit replaced = [r.sub('<1>', w) for w in words]
100 loops, best of 3: 6.15 ms per loop

as you can see for such simple patterns the accepted list comprehension is the fastest, but look at the following:

In [8]: %timeit replaced = [w.replace('1', '<1>').replace('324', '<324>').replace('567', '<567>') for w in words]
100 loops, best of 3: 8.25 ms per loop

In [9]: r = re.compile('(1|324|567)')

In [10]: %timeit replaced = [r.sub('<\1>', w) for w in words]
100 loops, best of 3: 7.87 ms per loop

This shows that for more complicated substitutions a pre-compiled reg-exp (as in 9-10) can be (much) faster. It really depends on your problem and the shortest part of the reg-exp.

Solution 5 - Python

An example with for loop (I prefer List Comprehensions).

a, b = '[br]', '<br />'
for i, v in enumerate(words):
    if a in v:
        words[i] = v.replace(a, b)
print(words)
# ['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEric HerlitzView Question on Stackoverflow
Solution 1 - PythonsberryView Answer on Stackoverflow
Solution 2 - PythonhoubysoftView Answer on Stackoverflow
Solution 3 - PythonAnthony KongView Answer on Stackoverflow
Solution 4 - PythonJörn HeesView Answer on Stackoverflow
Solution 5 - PythonWaket ZhengView Answer on Stackoverflow