ThanksInAdvance ThanksInAdvance - 8 months ago 36
Python Question

How can I replace all occurrences of a substring using regex?

I have a string,

s = 'sdfjoiweng%@$foo$fsoifjoi'
, and I would like to replace

I tried
re.sub(r'\bfoo\b', 'bar', s)
re.sub(r'[foo]', 'bar', s)
, but it doesn't do anything. What am I doing wrong?


You can replace it directly:

>>> import re
>>> s = 'sdfjoiweng%@$foo$fsoifjoi'
>>> print re.sub('foo','bar',s)

It will also work for more occurrences of foo like below:

>>> s = 'sdfjoiweng%@$foo$fsoifoojoi'
>>> print re.sub('foo','bar',s)

If you want to replace only the 1st occurrence of foo and not all the foo occurrences in the string then alecxe's answer does exactly that.