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:
- old : A substring that should be replaced.
- new : A new substring that will replace the old substring.
- 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.
mystr = 'Hello World!'
print(mystr.replace('Hello','Hi'))
mystr = 'apples, bananas, apples, apples, cherries'
print(mystr.replace('apples','lemons'))
Hi World!
lemons, bananas, lemons, lemons, cherries
The replace()
method performs case-sensitive search.
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
food Morning!
Good Morning!
Good Morninf!
The count
parameter specifies the maximum number of replacements should happen, as shown below.
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))
lemons, bananas, lemons, apples, cherries, apples
SQL, Java, Python, C are programming languages
The replace()
method can also be used on numbers and symbols
mystr = '100'
print(mystr.replace('1','2'))
mystr = '#100'
print(mystr.replace('#','$'))
200
$100
An empty string can also be passed to the new string parameter as a value.
mystr = 'Hello World'
print(mystr.replace('World',''))
Hello