Home / Python / Reference / String methods

Python string replace() method

Replace every occurrence of some text with other text.

Syntax

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

Replaces all occurrences unless you give count. Replacing with "" deletes. Strings cannot change, so this returns a new string; keep it with s = s.replace(…).

Parameters

oldthe text to find
newwhat to put instead
countthe most replacements to make

Return value

str

Example

Code

print("2026-11-17".replace("-", "/"))
print("a cat, a hat".replace("a ", "the "))
print("$1,234.50".replace("$", "").replace(",", ""))
print("aaa".replace("a", "b", 2))

Output

2026/11/17
the cat, the hat
1234.50
bba
Good to know. replace is case-sensitive: "Cat".replace("cat", "dog") changes nothing.

Related

Learn it step by step in the free lesson Strings, with exercises that check your answers.