String Replace in Python

To replace one or more occurrences of a substring in string in Python, with a new string, use string.replace() function.

In this tutorial, we will learn the syntax of string.replace() function and how to replace substring in a string using string.replace() via example programs.

Syntax of str.replace()

The syntax of string.replace() function is

string.replace(old, new, count)

where

ParameterOptional/MandatoryDescription
oldMandatoryA string. This substring will be replaced in this string.
newMandatoryA string. This new string is substituted in the place of old substring.
countOptionalAn integer. The number of occurrences of old substring to be replaced with new string.

By default, string.replace() replaces all the occurrences of old string with new string in the given string.

Return Value

A string.

The function returns the original string, from which old sub-string is replaced with new sub-string. If count is provided, the function replaces the old sub-string for its first count number of occurrences.

Replace All Occurrences

In this example, we will replace all the occurrences of old sub-string with new sub-string.

Example.py

s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'

s2 = s1.replace(old, new)
print(s2)
Try Online

Output

dog says hey. condog dogalog.

Replace only N Occurrences

In this example, we will replace only N occurrences of old sub-string with new sub-string.

Example.py

s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'

s2 = s1.replace(old, new, 2)
print(s2)
Try Online

Output

dog says hey. condog catalog.

In the input string s1, only the first two occurrences of the old sub-string is replaced.

Replace only First Occurrence

In this example, we will replace only the first occurrence of old sub-string with new string.

Example.py

s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'

s2 = s1.replace(old, new, 1)
print(s2)
Try Online

Output

dog says hey. concat catalog.

Conclusion

In this Python Tutorial, we learned how to use replace a substring in a given string using str.replace() function.