transformation

str.replace

Returns a new string with all occurrences of substring old replaced by new. If count is given, only the first count occurrences are replaced.

str.replace(old, new[, count])

Parameters

Parameter Purpose
old substring to search for
new substring to substitute in
count maximum number of replacements (default: all)

Examples

>>> 'hello world'.replace('world', 'there')
'hello there'

single replacement

>>> 'a.b.c.d'.replace('.', '-')
'a-b-c-d'

all occurrences replaced by default

>>> 'a.b.c.d'.replace('.', '-', 2)
'a-b-c.d'

count caps the number of replacements

>>> 'hello'.replace('l', '')
'heo'

empty `new` deletes the matches

Gotcha

Strings are immutable — replace returns a new string; the original is unchanged. For regex patterns use re.sub() instead.

Related methods

← All Python string methods · Python built-ins