Python String replace() Method

Replaces occurrences of a substring within a string


The replace() method returns a copy of string with all occurrences of old substring replaced by new.

By default, all occurrences of the substring are removed.

However, you can limit the number of replacements by specifying optional parameter count.



Python string replace() method parameters
oldRequiredA string you want to replace
newRequiredA string you want to replace old string with
countOptionalAn integer specifying number of replacements to perform
Default is all occurrences


Example: Replace substring ‘World’ with ‘Universe’

S = 'Hello, World!'
x = S.replace('World','Universe')
print(x)    # Hello, Universe!

By default, the method replaces all occurrences of the specified substring.

Example: Replace all occurrence of the substring ‘Long’

S = 'Long, Longer, Longest'
x = S.replace('Long','Small')
print(x)    # Small, Smaller, Smallest

If the optional argument count is specified, only the first count occurrences are replaced.

Example: Replace first two occurrence of the substring ‘Long’

S = 'Long, Longer, Longest'
x = S.replace('Long','Small', 2)
print(x)    # Small, Smaller, Longest