Replace all occurrences of a word in a string in Python
In this tutorial, we will learn how to replace all occurrences of a word in string and n occurrences of a substring in Python Programming.
replace() is a built-in function in Python Program, it is used to replace the strings in a statement. With the help of replace() function we can replace the strings in a statement or in a word, which returns the replaced string.
original_string = "Pythonlanguageissimpletolearn" replaced_string =original_string.replace("simple","easy") print(replaced_string)
Replace n Occurrences of a Substring in Python:
Here we can replace the strings in a Nth position. Then the third parameter will comes in the replace() function. Now we can see that “simple” is replaced with “easy” by the identify the position. Position indicates the Index of the string.
string.replace(old, new, n)
Original_string = " Python Programming language is simple to learn" Replaced_string = Original_string.replace("simple", "easy", 4) print(Replaced_string)
Python Programming language is easy to learn