Python String replace() Method

Replaces occurrences of a substring within a string

Usage

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.

Syntax

string.replace(old,new,count)

Python string replace() method parameters
ParameterConditionDescription
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

Examples

# Replace substring 'World' with 'Universe'
S = 'Hello, World!'
x = S.replace('World','Universe')
print(x)
# Prints Hello, Universe!

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

# Replace all occurrence of the substring 'Long'
S = 'Long, Longer, Longest'
x = S.replace('Long','Small')
print(x)
# Prints Small, Smaller, Smallest

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

# Replace first two occurrence of the substring 'Long'
S = 'Long, Longer, Longest'
x = S.replace('Long','Small', 2)
print(x)
# Prints Small, Smaller, Longest