Python Glossary Русский

all Python 3Strings (str)function

str.replace

replacement

Return a copy with all occurrences of old replaced by new (optional count limit).

Syntax

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

Strings are immutable, so replace hands back a new string and changes nothing in place — forgetting to assign the result is the single most common beginner slip. Scanning goes left to right and inserted text is not re-scanned, but a second replace in a chain will happily hit what the first one produced, which is why swapping two characters calls for translate instead. An empty old is a special case: new gets inserted between every pair of characters and at both ends.

Examples

print('a.b.c'.replace('.', '_'))    # → a_b_c
print('aaa'.replace('a', 'b', 2))   # → bba
print('hello'.replace('l', ''))     # → heo

See also

Open in the full glossarydocs.python.orgReport an inaccuracy