Python String replace() Method

The replace() method returns a copy of the string where all occurrences of a substring are replaced with another substring. The number of times substrings should be replaced by another substring can also be specified.

Syntax:

str.replace(old, new, count)

Parameters:

  1. old : A substring that should be replaced.
  2. new : A new substring that will replace the old substring.
  3. count : (Optional) An integer indicating the number of times you want to replace the old substring with the new substring.

Return Value:

Returns a new string that is replaced with the new substring.

The following examples demonstrate the replace() method.

Example: replace()
mystr = 'Hello World!'
print(mystr.replace('Hello','Hi'))

mystr = 'apples, bananas, apples, apples, cherries'
print(mystr.replace('apples','lemons'))
Output
Hi World!
lemons, bananas, lemons, lemons, cherries

The replace() method performs case-sensitive search.

Example: Case-sensitive Replace

mystr = 'Good Morning!'
print(mystr.replace('G','f')) # replace capital G

mystr = 'Good Morning!'
print(mystr.replace('good','food')) # can't find 'good'


mystr = 'Good Morning!'
print(mystr.replace('g','f')) # replace small g
Output
food Morning!
Good Morning!
Good Morninf!

The count parameter specifies the maximum number of replacements should happen, as shown below.

Example: replace() with Count
mystr = 'apples, bananas, apples, apples, cherries, apples'
print(mystr.replace('apples','lemons',2))

mystr = 'Python, Java, Python, C are programming languages'
print(mystr.replace('Python','SQL',1))
Output
lemons, bananas, lemons, apples, cherries, apples
SQL, Java, Python, C are programming languages

The replace() method can also be used on numbers and symbols

Example: Replace Numbers or Symbols
mystr = '100'
print(mystr.replace('1','2'))

mystr = '#100'
print(mystr.replace('#','$'))
Output
200
$100

An empty string can also be passed to the new string parameter as a value.

Example: Replace Empty String
mystr = 'Hello World'
print(mystr.replace('World',''))
Output
Hello