Python 3 reference · String Methods

Python String replace() Method

Return a copy with every occurrence of old replaced by new, or only the first count occurrences.

Python 3 Since 3.0

Syntax

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

Parameters

ParameterDescription
old The substring to replace.
new The replacement.
count optional Replace at most this many occurrences; -1 means all. Default: -1

Return value

A new string (strings are immutable, so the original is unchanged).

Examples

Replace all or just the firstTry it yourself
text = "I like cats. cats are great."
print(text.replace("cats", "dogs"))
print(text.replace("cats", "dogs", 1))

Output

I like dogs. dogs are great.
I like dogs. cats are great.
Remember to keep the resultTry it yourself
s = "hello"
s.replace("h", "J")  # result thrown away!
print(s)
s = s.replace("h", "J")
print(s)

Output

hello
Jello
Remove several charactersTry it yourself
phone = "(555) 123-4567"
for ch in "()- ":
    phone = phone.replace(ch, "")
print(phone)

Output

5551234567

Common mistakes

  • replace() doesn't change the string in place; assign the result.
  • It is case-sensitive. For patterns or case-insensitive replacement use re.sub().

Version history

VersionChange
Python 3.0Added
Python 3.13count can be passed as a keyword argument.