Python String Replace Method

In python, the string replace() method is useful to replace the specified substring or character in all occurrences of the given string.

 

Following is the pictorial representation of string replace() method functionality in python.

 

Python string replace method example result

 

If you observe the above diagram, we are replacing the "Hi" word in the given string “Hi Guest Hi” with "Hello" using the python replace method. After completing string replacement, the replace() method will return a new string like "Hello Guest Hello".

String Replace Method Syntax

Following is the syntax of defining a string replace method in python.

 

string.replace(old string/char, new string/char, count) 

If you observe the above syntax, the replace() method accepts three parameters (old string/char, new string/char, count), and the count parameter is optional.

 

  • old string/char - It’s the old string/character you want to replace.
  • new string/char - The new string/character will replace the old string/character.
  • count - It’s optional and useful to define the number of times the old substring to replace with the new substring.

String Replace Method Example

Following is the example of replacing all specified string occurrences using the replace() method in python.

 

msg1 = "Hi Guest Hi, Learn Python"
rmsg1 = msg1.replace("Hi","Hello")
msg2 = "aaaacc"
rmsg2 = msg2.replace("a","b")
msg3 = "1 2 3 4 5 6 7"
rmsg3 = msg3.replace(" ",",")
print(rmsg1)
print(rmsg2)
print(rmsg3)

If you observe the above example, we are replacing the substrings in the given strings with the required substrings/characters using the replace() method without specifying the count parameter.

 

When you execute the above python program, you will get the result as shown below.

 

Hello Guest Hello, Learn Python
bbbbcc
1,2,3,4,5,6,7

In the above example, we didn’t mention any limit (count) on the number of replacements. The replace() method replaced all the occurrences of substrings/characters in the given strings.

 

If you want to limit the number of strings replacement, you need to mention the count parameter value in the replace() method.

 

Following is the example of limiting the number of substrings replacement with count parameter value using replace() method.

 

msg1 = "Hi Guest Hi"
rmsg1 = msg1.replace("Hi","Hello")
rmsg2 = msg1.replace("Hi","Hello",0)
rmsg3 = msg1.replace("Hi","Hello",1)
print(rmsg1)
print(rmsg2)
print(rmsg3)

If you observe the above example, we are limiting the string replacement by specifying the count parameter value in replace() method.

 

When you execute the above python program, you will get the result as shown below.

 

Hello Guest Hello
Hi Guest Hi
Hello Guest Hi

This is how you can use a string replace() method in python to replace all substring occurrences in the given string based on your requirements.