Python String replace() Method

Replaces all occurrences of the substring with a new string. The number of occurrences can also be specified.

Syntax

Python
string.replace(old, new, count = -1)

Parameters

ParameterDescription
old Required. The string to search for
new Required. The string to replace the old string with
count Optional. The maximum number of times you want the replacement to occur. The default is -1 which means all occurrences of the old string are to be replaced by the new string.

Example

Python
str = 'The quick brown fox jumped over the lazy dog'
print(str.replace('fox', 'cow'))

str = 'Hello World'
print(str.replace('o', 'ow', 1)) # replace only the first 'o' with 'ow'

Output

The quick brown cow jumped over the lazy dog
Hellow World