Python Tutorial Python Advanced Python References Python Libraries

Python String - replace() Method



The Python replace() method returns the string where all occurrences of specified substring in the given string 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.

Return Value

Returns the string where all occurrences of specified substring in the given string is replaced by another specified string.

Example: Replace all occurrences of a substring

In the example below, 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'))

The output of the above code will be:

Python is a programming language. Learning Python is fun.

Example: Replace number of occurrences of a substring

In the example below, 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))

The output of the above code will be:

Python is a programming language. Learning Java is fun.

❮ Python String Methods