Python String replace() Method



The Python String replace() method replaces all occurrences of one substring in a string with another substring. This method is used to create another string by replacing some parts of the original string, whose gist might remain unmodified.

For example, in real-time applications, this method can be used to replace multiple same spelling mistakes in a document at a time.

This replace() method can also replace selected number of occurrences of substrings in a string instead of replacing them all.

Syntax

Following is the syntax for Python String replace() method −

str.replace(old, new[, count])

Parameters

  • old − This is old substring to be replaced.

  • new − This is new substring, which would replace old substring.

  • count − If this optional argument count is given, only the first count occurrences are replaced.

Return Value

This method returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

Example

The following example shows the usage of Python String replace() method.

str = "Welcome to Tutorialspoint"
str_replace = str.replace("o", "0")
print("String after replacing: " + str_replace)

When we run above program, it produces following result −

String after replacing: Welc0me t0 Tut0rialsp0int

Example

When we pass the substring parameters along with the optional count parameter, the method only replaces the first count occurrences in the string.

In this example below, the input string is created and the method takes three arguments: two substrings and one count value. The return value will be the string obtained after replacing the first count number of occurrences.

str = "Fred fed Ted bread and Ted fed Fred bread."
strreplace = str.replace("Ted", "xx", 1)
print("String after replacing: " + strreplace)

When we run above program, it produces following result −

String after replacing: Fred fed xx bread and Ted fed Fred bread.

Example

When we pass two substrings and count = 0 as parameters to the method, the original string is returned as the result.

In the following example, we created a string "Learn Python from Tutorialspoint" and tried to replace the word "Python" with "Java" using the replace() method. But, since we have passed the count as 0, this method does not modify the current string, instead of that, it returns the original value ("Learn Python from Tutorialspoint").

str = "Learn Python from Tutorialspoint"
strreplace = str.replace("Python", "Java", 0)
print("String after replacing: " + strreplace)

If you execute the program above, the outpit is displayed as −

String after replacing: Learn Python from Tutorialspoint
python_strings.htm
Advertisements