Python replace() Function

The replace() function in Python is used when we need to replace some part of string (old phrase) with another (new phrase), in a string. For example:

str = "This is fresherearth"
print("The string is:", str)

str = str.replace("fresherearth", "Python Programming")
print("\nNow the string is:", str)

The snapshot given below shows the sample output of above program, demonstrating the replace() function:

python replace function

Python replace() Function Syntax

The syntax of replace() function in Python, is:

string.replace(oldPhrase, newPhrase, count)

The function replace() returns the new version of the string, after replacing the oldPhrase with newPhrase. The third parameter, that is the count parameter is optional, and is used to specify the occurrence of oldPhrase to replace.

Note: The default value of count is basically the all occurrence of oldPhrase to replace with newPhrase.

Python replace() Function Example

Here is an example of replace() function in Python. This program allows user to define the string as well as old and new phrases to perform the replace operation using, of course, the replace() function:

print("Enter the String: ", end="")
str = input()

print("\nEnter the Old Phrase to Replace: ", end="")
oldPhrase = input()
print("Enter the New Phrase: ", end="")
newPhrase = input()

str = str.replace(oldPhrase, newPhrase)
print("\nThe string is:", str)

The sample run with user input that was not was only the was as string data, was as old phrase, and python as new phrase, to replace was with python:

python replace function example

And if you want to remove old phrase with new phrase, but only for particular number of occurrence. For example, to remove was with python for only 2 occurrences. Then use the following code:

str = str.replace(oldPhrase, newPhrase, 2)

Now the output with same user input, comes out to be:

python replace function program

Since there are 3 was in the given string, but we need to replace only 2 was, therefore the last was is still available in the string, after replacing was by python, for only 2 occurrences.

Python Online Test


« Previous Function Next Function »