Computer >> Computer tutorials >  >> Programming >> Python

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


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")
'chihahhah'

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')
'chihahhah'

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