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
| Parameter | Description |
|---|---|
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
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.
s = "hello"
s.replace("h", "J") # result thrown away!
print(s)
s = s.replace("h", "J")
print(s)
Output
hello Jello
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
| Python 3.13 | count can be passed as a keyword argument. |
Related
str.translate()· Return a copy where each character is mapped through a translation table, replacing or deleting characters fast.str.maketrans()· Create a translation table for translate(): map characters to replacements, or to None to delete them.str.removeprefix()· Return the string without the given prefix if it starts with it; otherwise return it unchanged.str.strip()· Return a copy with leading and trailing characters removed: whitespace by default, or any of the characters you pass.- Python Strings · tutorial