The method replace() is a built-in function in Python programming that returns all the old substring occurrences with the new substring, optionally restricting the number of replacements to the max.
The syntax of the method is: str.replace(old, new[, max])
Key Points :
• It is used to replace a string with another string and returns the result after replacement.
• The original string is not changed by this method.
• This function returns a replica of a string where a substring replaces any substring occurrences.
• In layman’s terms, the old substring is replaced with the new substring and returns the string’s copy; one point to note is that the original string is not changed.
• This method is classified as <class ‘str’>.
We’ll be covering the following topics in this tutorial:
replace() parameters
Below is a definition of the replace() parameters since three parameters are present:
• old: it is a necessary attribute to define the search substring.
• new: it is a compulsory attribute used to specify the value to replace.
• count: this is an optional parameter and a number used to show how many occurrences you choose to replace with the old value.
Note: The replace() method will overwrite all the old substring occurrences by the new substring if count is not specified.
Return Value from replace()
• The replace() function returns a copy of the string where the new substring replaces the old substring. The original string stays the same.
• If the old substring is not found, the copy of the original string will restore.
Below is the python program to demonstrate the replace() function:
str = "Different foxes, gray fox, red fox, arctic fox";
print (str.replace("fox", "dog"))
print (str.replace("fox", "dog", 2))
When we run above the program, the outcome is as follows:
Different doges, gray dog, red dog, arctic dog
Different doges, gray dog, red fox, arctic fox
Python String replace() with RegExp
import re str = "The Best Learning Resource For Online Education" res = re.sub("\s", "||", str) print(res)
When we run above the program, the outcome is as follows:
The||Best||Learning||Resource||For||Online||Education
Python Remove Character from String using replace() Method
str = "The Best Learning Resource for Online Education" print (str) res_str = str.replace('n', '') # removes all occurrences of 'n' print (res_str) # Removing 1st occurrence of n res_str = str.replace('n', '', 1) print (res_str)
When we run above the program, the outcome is as follows:
The Best Learning Resource for Online Education
The Best Learig Resource for Olie Educatio
The Best Learing Resource for Online Education
Below are several other functions that we can use to work with string in Python 3