Python String replace() Method
The replace() method replaces the old (old string) in the string with the new (new string), and if the third argument max is specified, it replaces it no more than max times.
Python String replace() Syntax
Replace() method syntax.
str.replace(old, new[, max])
Python String replace() Parameters
- old – the substring that will be replaced.
- new – the new string to replace the old substring.
- max – optional string, replace no more than max times
Python String replace() Return Value
Returns the new string generated by replacing old (old string) with new (new string), if the third parameter max is specified, the replacement will not exceed max times.
Python String replace() Example#1
The following example shows the use of the replace() function, where we use the replace() function to replace all api’s with apidemos.
#!/usr/bin/python3
string = "api1 api2 api3 api4 welcome to apidemos.com"
print(string)
print(string.replace("api", "apidemos"))
Output:
Python String replace() Example#2
Use replace() to replace a single character, in this case, a character from a given string.
The Python replace() method is case-sensitive, so it performs a case-sensitive substring replacement, which means that the R in FOR is unchanged.
#!/usr/bin/python3
string = "api FOR demos, apidemoer"
# replace all instances of 'r' with 'e'
new_string = string.replace("r", "e" )
print(string)
print(new_string)
Output: