String replacement is often essential. If you want to replace any string or word in your program, then one option is to manually check the whole program and replace each string with the desired string. Python also provides a built-in replace() function for string replacement. The Python replace() function does not replace the actual string, but it makes a copy of the string, and replaces instances of the specified string with the new string. This article shows you how to use the replace() function in Python.

Syntax

The syntax of the replace() function is as follows:

string.replace(oldstring, newstring,count)

Old String: The string that you want to replace.

New String: The string that replaces the old string.

Count: This parameter is optional. The count parameter is used to state the number of times you wish to replace the old string with the new string.

The replace() function only returns the copy of the string.

Examples

We will now look at some examples of the Python replace() function. In the example given below, we will replace the term “website” with the term “linuxhint.”

# declaring the original string

str=“Hello and welcome to the website”

# replacing the “website” with “linuxhint”

print(“The replaced string is: “,str.replace(“website”,“linuxhint”))

Output

The output is displayed in the Python console. This output shows that the term “website” has been replaced with the term “linuxhint.”

Python String replace() Function Python