AppDividend
Latest Code Tutorials

Python String Replace Example | Replace() Method Tutorial

0

Python String Replace Example | Replace() Method Tutorial is today’s topic. The replace() method returns the copy of the string where all occurrences of the substring are replaced with another substring. The String replace() method replaces the specified phrase with another specified phrase. All occurrences of the specified phrase will be replaced if nothing is specified on the function argument. The replace() method returns the copy of the string in which the values of old string have been replaced with the new value.

Python String Replace Example

The syntax is following.

string.replace(oldvalue, newvalue, count)

The oldvalue parameter is required, and it is the value we need to search for.

The newvalue parameter is required, and it is the value we need to replace with.

The count parameter is optional, and it is a number specifying how many occurrences of the old value you want to replace.

Let’s see the example.

# app.py

line = 'Every DC Movies are great movies'

replacedString = line.replace('DC', 'Marvel')

print(replacedString)

In the above example, we are replacing the DC substring with the Marvel.

See the output below.

 

Python String Replace Example

Here one thing is to notice that the original string is unchanged.

Let’s see the example where we will specify how many times, you need to change the occurrences.

# app.py

line = 'Every DC Movies are great Movies!! Really great Movies'

replacedString = line.replace('Movies', 'Cartoons', 2)

print(replacedString)

In the above example, we are changing only two times from Movies to Cartoons.

 

Python String Replace Example | Replace() Method Tutorial

More Example on Python String replace()

See the below examples.

# app.py

str = 'cold, cold heart'
replaced_str =  str.replace('o', 'e')
print ('Original string:', str)
print ('Replaced string:', replaced_str)

str = 'let it be, let it be, let it be'
print(str.replace('let', 'so', 0))

See the output.

 

More Example on Python String replace()

Finally, Python String Replace Example | Replace() Method Tutorial is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.