How to use the Python String replace() Method
The Python string replace()
method is used to find substrings in a string and replace them with a new value (or an empty string).
In this tutorial, we will learn how to search for occurrences of a substring and replace them with a new string.
String replace() Syntax
The syntax of replace()
is:
string.replace(old, new, [limit])
replace()
is always placed after the string to search in using a .
(dot). It uses two required arguments and one optional argument:
old
- the substrings to replace wrapped in''
(single quotations) or""
(double quotations)new
- the new string to replace occurrences of old with wrapped in''
(single quotations) or""
(double quotations)limit
- the maximum number of occurrences to replace (optional)
Basic Usage
Let's replace all occurrences of a word in a string with a new word. replace()
returns a new string with the updated values, which we will store in a variable before printing the final result.
string = "two plus two is... three plus three is..."
new_str = string.replace('two', 'four')
print(new_str)
four plus four is... three plus three is...
Replace only the First Occurance in a String
To replace only the first substring or another limited number of matches, pass the number in the third argument of replace()
.
string = "two plus two is... three plus three is..."
new_str = string.replace('two', 'four', 1)
print(new_str)
four plus two is... three plus three is...
Replace Characters in a String
replace()
can be used to replace individual characters in a string.
string = "col cop"
new_str = string.replace('o', 'a')
print(new_str)
cal cap
Conclusion
You now know how to replace substrings of a string in Python.