In this Python tutorial, we will learn the syntax of string.replace() function and how to replace substring in a string using string.replace() via example programs.
Python – String Replace
To replace one or more occurrences of a substring in string in Python, with a new string, use string.replace() function.
Syntax of str.replace()
The syntax of string.replace() function is
string.replace(old, new, count)
where
Parameter | Optional/ Mandatory | Description |
---|---|---|
old | Mandatory | A string. This substring will be replaced in this string. |
new | Mandatory | A string. This new string is substituted in the place of old substring. |
count | Optional | An 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.
Examples
1. Replace All Occurrences
In this example, we will replace all the occurrences of old sub-string with new sub-string.
Python Program
s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'
s2 = s1.replace(old, new)
print(s2)
Output
dog says hey. condog dogalog.
2. Replace only N Occurrences
In this example, we will replace only N occurrences of old sub-string with new sub-string.
Python Program
s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'
s2 = s1.replace(old, new, 2)
print(s2)
Output
dog says hey. condog catalog.
In the input string s1
, only the first two occurrences of the old sub-string is replaced.
3. Replace only First Occurrence
In this example, we will replace only the first occurrence of old sub-string with new string.
Python Program
s1 = 'cat says hey. concat catalog.'
old = 'cat'
new = 'dog'
s2 = s1.replace(old, new, 1)
print(s2)
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.