Python Replace String

Replace String in Python

You can replace a word or substring in a string in Python programming.

To replace a String in Python, you can use replace() method on the String. In this tutorial, we will how to use replace() method to replace all or only maximum number of occurrences.

Python String Replace

Syntax of replace()

The syntax of replace() method is:

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

where old string is replaced with new string in str string for count number of times.

count is optional. So, if you do not provide count, all the occurrences of old substring will be replaced with new substring.

Example 1: Replace a String in Python

In the following example, we have a string. In that string, we will replace Examples string with Programs string using replace() method.

Python Program

mystring = 'Python Examples. Examples for basic and advanced concepts.'
print('Original String :',mystring)

newstr = mystring.replace('Examples', 'Programs')
print('New String :',newstr)
Run

Output

Original String : Python Examples. Examples for basic and advanced concepts.
New String : Python Programs. Programs for basic and advanced concepts.

Example 2: Replace String only a Specific Number of Times

In this example, we will replace the old string with new one only a specific number of times.

Python Program

mystring = 'Python Examples. Examples. Examples. Examples. Examples. Examples.'
print('Original String :',mystring)

newstr = mystring.replace('Examples', 'Programs', 3)
print('New String :',newstr)
Run

Output

Original String : Python Examples. Examples. Examples. Examples. Examples. Examples.
New String : Python Programs. Programs. Programs. Examples. Examples. Examples.

The old string is replaced with new string only 3 times, which we provided as a third argument to the method.

Summary

In this tutorial of Python Examples, we learned how to replace a substring with another string (only a specific number occurrences or all occurrences) with the help of well detailed examples.