Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

str.replace

Replaces occurrences of a literal substring, optionally stopping after a maximum number.

Version: Python 3.14; repository image, production runtime not attested

Syntax

s.replace(old, new, /, count=-1)

Replaces occurrences of a literal substring, optionally stopping after a maximum number.

An empty search string inserts the replacement at boundaries between characters and at both ends.

By default every non-overlapping literal match is replaced. A limit of two changes only the first two a characters. An empty old string matches the three boundaries of ab, producing the five-character string ".a.b.".

assert "aaaa".replace("aa", "X", count=1) == "Xaa"

Examples

print("a-a-a".replace("a", "X", 2))
print("ab".replace("", "."))

Result

X-X-a
.a.b.

By default every non-overlapping literal match is replaced. A limit of two changes only the first two a characters. An empty old string matches the three boundaries of ab, producing the five-character string ".a.b.".

Sources