replace() looks for a piece of text, called old, and swaps every copy of it for new. "banana".replace("a", "o") is "bonono". If old is not found, you get the same text back and no error is raised.
An optional count limits the swap to the first few matches, counted from the left. The search is case-sensitive. Replacing with an empty string "" is the easy way to remove text. Strings never change in place, so the method returns a new string.
text.replace() is a method of the built-in str type: call it on a string with dot notation. No import is needed, and it never changes the original string.
Syntax
Pass the text to find and the text to put in its place. count is optional.
python
result = text.replace(old, new)
result = text.replace(old, new, count)
Call
What it does
"banana".replace("a", "o")
Returns 'bonono'. All three a letters are replaced.
"banana".replace("a", "o", 2)
Returns 'bonona'. Only the first two matches are replaced.
"hello".replace("z", "y")
Returns 'hello'. The substring is not found, so nothing changes.
To change many single characters in one pass use translate(). To cut a string into pieces use split(), and for patterns instead of fixed text use the re.sub() function from the re module.
Library declarations
python
str.replace(old, new[, count]) -> str
# returns: a new string with the replacements made
# raises: TypeError if old or new is not a string
Parameters
Parameter
Description
old
Required. The substring to look for. It must be a string. An empty string matches between every character.
new
Required. The text to put in its place. It must be a string, and it can be empty to remove the matches.
count
Optional. The maximum number of replacements, counted from the left. Default -1, which means replace all matches.
Return Value
Return Value
Description
str
A new string with the replacements made. If nothing matched, the result equals the original. The original string is not changed.
Python Examples
Example 1 — Swap a Word in a Sentence
Replace text, see that the search is case-sensitive, and check that the original stays the same.
python
text = "I like cats. Cats are cute."
print(text.replace("cats", "dogs"))
print(text.replace("Cats", "Dogs"))
print(text.replace("cats", "dogs").replace("Cats", "Dogs"))
print(text)
Output
I like dogs. Cats are cute.
I like cats. Dogs are cute.
I like dogs. Dogs are cute.
I like cats. Cats are cute.
How It Works
Lower case only."cats" matches the first word, but "Cats" with a capital letter is left alone.
The other spelling. Searching for "Cats" replaces only the capitalised word.
Chain two calls. Each replace() returns a string, so a second call can handle the other spelling, and both words change.
The original is unchanged. The last line still shows the first sentence.
Example 2 — Replace All, Some, or None
Use the count argument, and an empty string to remove text.
python
date = "2024/05/01"
print(date.replace("/", "-"))
print(date.replace("/", "-", 1))
print(date.replace("/", ""))
Output
2024-05-01
2024-05/01
20240501
How It Works
Replace all. Without count, both slashes become hyphens.
Replace one. With count set to 1, only the first slash is replaced.
Remove text. An empty string as the new text deletes every slash.
Example 3 — Clean a Phone Number
Remove several characters in a loop, then see what an empty search text does.
python
phone = "(555) 123-4567"
digits = phone
for char in "()- ":
digits = digits.replace(char, "")
print(digits)
print("abc".replace("", "-"))
Output
5551234567
-a-b-c-
How It Works
One character at a time. The loop visits each character of "()- ", which are the two brackets, the hyphen, and the space.
Keep updating the variable. Each call works on the result of the last one, so digits ends up with only digits.
An empty search text."abc".replace("", "-") puts a hyphen between every character and at both ends, which is almost never intended.
Frequently Asked Questions
It returns a copy of the string where every occurrence of a substring is replaced by another substring. You can limit the number of replacements with the count argument.
No. Strings are immutable, so replace() returns a new string. Assign the result, for example text = text.replace("a", "b").
Yes. "Cat" and "cat" are different. To ignore case, use re.sub() with the re.IGNORECASE flag.
Replace it with an empty string, for example text.replace("-", "").
Chain several replace() calls, loop over the characters, or use translate() with a table made by str.maketrans().