Python String replace() Method
text.replace(old, new, count=-1) returns a new string in which every occurrence of old is replaced by new, or only the first count occurrences if you give a count.replace() is the simplest way to fix text: change a word, remove unwanted characters, or swap a separator. It searches for an exact, case-sensitive substring, so it is not a pattern matcher; for patterns use the regex module.
Because strings are immutable, the original text stays as it was. You must save the returned string if you want to keep the change.
| Syntax | text.replace(old, new, count=-1) |
|---|---|
| Parameters | old: substring to find; new: replacement; count (optional): maximum number of replacements |
| Returns | A new str |
| Time complexity | O(n) in the length of the string |
How replace() finds and swaps substrings
Python scans from left to right, and each match is replaced by new. Matches do not overlap. The search is case-sensitive, so "Cat" does not match "cat". If old is not found, you get back an equal copy of the string with no error.
sentence = "cats chase cats"
print(sentence.replace("cats", "dogs"))
print(sentence.replace("Cats", "dogs"))Replacing only the first few matches with count
The optional third argument limits how many replacements happen, counting from the left. Pass it as a positional argument or as count= (keyword form is supported since Python 3.13). A count of 0 makes no replacement.
text = "a-b-c-d"
print(text.replace("-", "+", 1))
print(text.replace("-", "+", 2))
print(text.replace("-", ""))Replacing with an empty string, as in the last line, deletes the match.
replace() vs translate() vs re.sub()
| Tool | Best for | Case-insensitive? | Example |
|---|---|---|---|
replace() | One exact substring | No | s.replace("a", "b") |
Chained replace() | A few different substrings | No | s.replace("a", "b").replace("c", "d") |
str.translate() | Many single-character swaps at once | No | s.translate(table) |
re.sub() | Patterns, optional flags | Yes, with re.IGNORECASE | re.sub(r"\d+", "#", s) |
| Slicing + concatenation | Replacing by position | Not applicable | s[:2] + "X" + s[3:] |
Common uses: cleaning and formatting text
Typical jobs are removing spaces (replace(" ", "")), turning a title into a slug (replace(" ", "-")), or masking a character. When you need several replacements, chain the calls; they run in order, so later calls see the output of earlier ones. See removing whitespace from a string for the full set of options.
Examples you can run
Press Run, then edit the code and run it again.
Replace a word everywhere
All matches are replaced.
message = "Hello, world! Hello, Python!"
print(message.replace("Hello", "Hi"))Expected outputHi, world! Hi, Python!
Limit the replacements with count
Only the first match changes.
path = "a/b/c/d"
print(path.replace("/", "\\", 1))
print(path.replace("/", " > "))Expected outputa\b/c/d
a > b > c > d
Chain replace() calls to build a slug
Each call works on the result of the previous one.
title = "Learn Python: Strings & Lists"
slug = title.lower().replace(":", "").replace("&", "and").replace(" ", "-")
print(slug)Expected outputlearn-python-strings-and-lists
Common mistakes
Expecting the original string to change
✗ Wrong
name = "Asha Rao"
name.replace("Asha", "Ravi")
print(name)✓ Right
name = "Asha Rao"
name = name.replace("Asha", "Ravi")
print(name)Assign the result back to a variable.
Forgetting that matching is case-sensitive
✗ Wrong
print("Red red RED".replace("red", "blue"))✓ Right
import re
print(re.sub("red", "blue", "Red red RED", flags=re.IGNORECASE))Normalise the case first, or use re.sub() with re.IGNORECASE.
Replacing inside words by accident
✗ Wrong
print("cat concatenate".replace("cat", "dog"))✓ Right
import re
print(re.sub(r"\bcat\b", "dog", "cat concatenate"))replace() ignores word boundaries. Use re.sub(r"\bcat\b", ...) to match whole words.
Python String replace() Method: questions people ask
Does replace() change the original string in Python?
No. Strings are immutable, so replace() returns a new string and the original is unchanged.
How do I replace only the first occurrence of a character in a string?
Pass a count of 1: text.replace("a", "b", 1).
How do I replace multiple different characters in a string?
Chain several replace() calls, or use str.translate() for single characters or re.sub() for patterns.
Keep learning
Step-by-step lessons:
Python StringsPython String Methods
Related:
Python String find() MethodHow to Remove Whitespace from a String in PythonPython String strip() MethodPython Regular Expressions (regex)How to Check if a String Contains a Substring in Python
More in string methods:
Python String split() MethodPython String join() MethodPython String strip() MethodPython String lstrip() MethodPython String rstrip() MethodPython String upper() MethodPython String lower() MethodPython String title() Method See all →