The replace Method in Python: Replacing Substrings in a String

Returns a copy of the string with all occurrences of a specified substring replaced by a specified value.

replace(old, new[, count])

  • old -- substring to be replaced
  • new -- substring to replace the old one
  • count=None -- maximum number of replacements. If not specified, all occurrences will be replaced.
my_str = 'barbarian'
my_str = my_str.replace('bar', 'mur')  # 'murmurian'
my_str = my_str.replace('mur', 'bur', 1)  # 'burmurian'