Python String | replace method
Start your free 7-days trial now!
Python's str.replace(~)
method returns a new copy of the string with all occurrences of the old
substring replaced by the new
substring.
Parameters
1. old
| string
The substring to be replaced by new
.
2. new
| string
The substring to replace old
substring with.
3. count
| number
| optional
The number of occurrences of the old
substring to replace. Defaults to all occurrences.
Return value
Returns a new copy of the string with all occurrences of the old
substring replaced by the new
substring.
If count
argument is provided, only the first count
occurrences will be replaced.
Examples
Basic usage
To replace all occurrences of "Hi"
with "Hello"
:
x = "Hi Hi Hi!"x.replace('Hi', 'Hello')
'Hello Hello Hello!'
We can see that all occurrences of 'Hi'
are replaced by 'Hello'
in the returned string.
Count parameter
To replace only the first two occurrences of 'Hi'
:
y = "Hi Hi Hi!"y.replace('Hi', 'Hello', 2)
'Hello Hello Hi!'
We can see that only the first two occurrences of 'Hi'
are replaced by 'Hello'
in the returned string.