Python Function Reference

str.replace

Replace occurrences of the substring old with new.

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

Parameters

oldstr
The substring to replace.
newstr
The substring to put in its place.
countintoptional
How many first occurrences to replace; -1 means all.

Return value

A new string with the replacements; the original is not changed.

Examples

Replacing a word in a string

Python 3.13
print('hello world'.replace('world', 'Python'))
hello Python

Replacing only the first match

Python 3.13
print('a-b-c'.replace('-', '+', 1))
a+b-c

Details

Strings are immutable, so save the result: text = text.replace(...). The replacement is case-sensitive. To replace by a pattern, such as all digits, use re.sub.

See also

Where to learn