Skip to content
String Methods

replace()

Replace matching text with new text.

str.replace(old, new, count=-1)

str.replace() returns a copy of the string with all occurrences of substring old replaced by new.

The optional count parameter limits the number of replacements performed from left to right.

Parameters

NameDescription
oldThe text to replace.
newReplacement text.
countOptional maximum number of replacements; by default all matches are replaced.

Returns

A new string with replacements made.

Try it

Run it and change it
text = "one fish two fish"
print(text.replace("fish", "cat", 1))

Worth knowing

  • Immutability: Strings in Python are immutable; replace() always returns a new string and does not alter the original.

Related entries