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

You can replace it directly:

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

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

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

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.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)