Skip to content Skip to sidebar Skip to footer

Replacing Multiple Items With Regex In Python

I have a text file that contains certain string sequences that I want to modify. For example, in the following string I would like to replace foo and bar each with a unique string

Solution 1:

Option 1

I would recommend this for complicated scenarios. Here's a solution with re.sub and a lambda callback:

In [1]: re.sub('foo|bar', lambda x: 'fooNew' if x.group() == 'foo' else 'bar_replaced', text)
Out[1]: 'fooNew text text bar_replaced text'

Option 2

Much simpler, if you have hardcoded strings, the replacement is possible with str.replace:

In [2]: text.replace('foo', 'fooNew').replace('bar', 'bar_replaced')
Out[2]: 'fooNew text text bar_replaced text'

Post a Comment for "Replacing Multiple Items With Regex In Python"