How to replace all occurrences of a string with another string in Python?

PythonServer Side ProgrammingProgramming

Pyhton has a method called replace in string class. It takes as input the string to be replaced and string to replace with. It is called on a string object. You can call this method in the following way to replace all 'no' with 'yes':

>>> 'no one knows how'.replace('no', 'yes')
'yes one kyesws how'
>>> "chihuahua".replace("hua", "hah")

The re module in python can also be used to get the same result using regexes. re.sub(regex_to_replace, regex_to_replace_with, string) can be used to replace the substring in string.

For example,

>>> import re
>>> re.sub('hua', 'hah', 'chihuahua')

re.sub is very powerful and can be used to make very subtle substitutions using regexes.

Updated on 30-Sep-2019 06:08:10