Replace all occurrences of one substring with another substring

suggest change

Python’s str type also has a method for replacing occurences of one sub-string with another sub-string in a given string. For more demanding cases, one can use re.sub.

str.replace(old, new[, count]):

str.replace takes two arguments old and new containing the old sub-string which is to be replaced by the new sub-string. The optional argument count specifies the number of replacements to be made:

For example, in order to replace 'foo' with 'spam' in the following string, we can call str.replace with old = 'foo' and new = 'spam':

>>> "Make sure to foo your sentence.".replace('foo', 'spam')
"Make sure to spam your sentence."

If the given string contains multiple examples that match the old argument, all occurrences are replaced with the value supplied in new:

>>> "It can foo multiple examples of foo if you want.".replace('foo', 'spam')
"It can spam multiple examples of spam if you want."

unless, of course, we supply a value for count. In this case count occurrences are going to get replaced:

>>> """It can foo multiple examples of foo if you want, \
... or you can limit the foo with the third argument.""".replace('foo', 'spam', 1)
'It can spam multiple examples of foo if you want, or you can limit the foo with the third argument.'

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents