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():

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.

Syntax:

string.replace(old,new)

Example:

original_string = "Pythonlanguageissimpletolearn"
replaced_string =original_string.replace("simple","easy")
print(replaced_string)

Output:

Pythonlanguageiseasytolearn

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.

Syntax:

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)

Output:

Python Programming language is easy to learn

Also read: Replace comma with a new line in a text file using Python

Leave a Reply

Your email address will not be published. Required fields are marked *