Python replace() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
String

Definition

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)
CallWhat 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

ParameterDescription
oldRequired. The substring to look for. It must be a string. An empty string matches between every character.
newRequired. The text to put in its place. It must be a string, and it can be empty to remove the matches.
countOptional. The maximum number of replacements, counted from the left. Default -1, which means replace all matches.

Return Value

Return ValueDescription
strA 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)

How It Works

  1. Lower case only. "cats" matches the first word, but "Cats" with a capital letter is left alone.
  2. The other spelling. Searching for "Cats" replaces only the capitalised word.
  3. Chain two calls. Each replace() returns a string, so a second call can handle the other spelling, and both words change.
  4. 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("/", ""))

How It Works

  1. Replace all. Without count, both slashes become hyphens.
  2. Replace one. With count set to 1, only the first slash is replaced.
  3. 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("", "-"))

How It Works

  1. One character at a time. The loop visits each character of "()- ", which are the two brackets, the hyphen, and the space.
  2. Keep updating the variable. Each call works on the result of the last one, so digits ends up with only digits.
  3. 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().

Next: rfind()

Return the index of the last match of a substring, or -1 if it is missing.

rfind() tutorial →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

13 people found this page helpful