Python - String replace() Method


Advertisements

The Python string replace() method is used to return a copy of string where all occurrences of specified substring is replaced by another specified string. This method has one optional parameter which can be used to specify number of occurrences of substring which need to be replaced.

Syntax


string.replace(OldValue, NewValue, Count)

Parameters

OldValue Required. Specify substring which need to be replaced from the string.
NewValue Required. Specify substring to replace the old substring with from the string.
Count Optional. Specify number of occurrences of the old value need to be replaced with new value. Default is all occurrences.

Example: Replace all occurrences of a substring

In the below example, the string replace() method is used to replace all occurrences of substring Java with new substring Python.

MyString = 'Java is a programming language. Learning Java is fun.'

#replace all occurrences of 'Java' with 'Python'
print(MyString.replace('Java', 'Python'))

Output

Python is a programming language. Learning Python is fun.

Example: Replace number of occurrences of a substring

In the below example, the string replace() method is used to replace only first occurrence of substring Java with new substring Python by assigning value 1 to the optional argument Count.

MyString = 'Java is a programming language. Learning Java is fun.'

#replace first occurrence of 'Java' with 'Python'
print(MyString.replace('Java', 'Python', 1))

Output

Python is a programming language. Learning Java is fun.

String Methods
Advertisements