Sub topic 8
Replacing text
This chapter covers str.replace, the basic tool for substituting one piece of text with another. It assumes you know what str literals are, how to call a method, and how to read a simple for loop. It also builds on the previous chapters, where you saw that strings never change in place.
The shape of replace
The signature is s.replace(old, new, count=-1). It returns a new string in which occurrences of old are replaced by new. The original string is untouched, so you must assign the result to keep it.
s = "banana"
t = s.replace("a", "o")
print(s) # banana
print(t) # bononoA common mistake is calling s.replace("a", "o") on its own line and expecting s to change. Python raises no error, and the replacement is silently thrown away.
By default every occurrence is replaced. A third argument limits how many replacements are made, counting from the left.
print("a-b-c".replace("-", "+")) # a+b+c
print("a-b-c".replace("-", "+", 1)) # a+b-c
print("a-b-c".replace("-", "+", 0)) # a-b-c
print("2024-01-15".replace("-", "/", 1)) # 2024/01-15A count of 0 makes no replacements. A negative count, including the default -1, means "all". Since Python 3.13 you can also pass it as a keyword, as in replace("-", "+", count=1). Older versions accept it only by position.
How the scan works
replace reads the string from left to right. At each position it checks whether old starts there. If it does, it emits new and jumps past the matched text. If it does not, it copies one character and moves on.
Three behaviors follow from this scan.
Matches do not overlap
Once a stretch of text is matched, it cannot be part of another match. This is the same rule count uses.
print("aaaa".replace("aa", "b")) # bb
print("aaa".replace("aa", "b")) # baIn "aaa" the first two characters match and are replaced. The remaining single a has no partner, so it stays.
Replaced text is not rescanned
The scan skips past the matched text and never looks at the text it inserted. This is why a replacement that contains its own search text does not loop forever.
print("aa".replace("a", "aa")) # aaaaMatching is exact and case sensitive
replace compares characters one by one. "Hello" and "hello" are different.
print("Hello hello".replace("hello", "hi")) # Hello hiIf you need to ignore case, replace cannot do it directly. You can lowercase the whole string first, but that changes the other characters too. For a case-insensitive replacement, the usual tool is re.sub with the re.IGNORECASE flag, covered in the last chapter of this tutorial.
Quick reference
| Call | Result | Why |
|---|---|---|
| `"a-b-c".replace("-", "")` | `abc` | An empty `new` deletes the matches |
| `"a-b-c".replace("x", "y")` | `a-b-c` | No match, so the content is unchanged |
| `"cat".replace("cat", "dog", 0)` | `cat` | `count=0` replaces nothing |
| `"Straße".replace("ß", "ss")` | `Strasse` | Works on any Unicode character |
| `"abc".replace("", "-")` | `-a-b-c-` | An empty `old` matches between characters |
Deleting text
Passing an empty string as new removes the matched text. This works well for small cleanups.
phone = "(555) 123-4567"
digits = phone.replace("(", "").replace(")", "").replace(" ", "").replace("-", "")
print(digits) # 5551234567Four chained calls work, but they read poorly as the list of characters grows. The translate chapter shows a one-pass alternative for single characters.
The empty search string
If old is empty, it matches at every position between characters, including both ends.
print("abc".replace("", "-")) # -a-b-c-
print("abc".replace("", "-", 2)) # -a-bcThis is rarely what you want. It usually appears when old comes from user input or a variable that turned out to be empty. If you pass variable data as old, guard against "" first.
def safe_replace(text, old, new):
if not old:
raise ValueError("old must not be empty")
return text.replace(old, new)
print(safe_replace("a-b", "-", "+")) # a+bReplacing many things
A common task is to apply several substitutions, such as filling placeholders in a template. A loop over a dictionary keeps this readable.
template = "Dear {name}, your order {order} shipped."
values = {"{name}": "Ana", "{order}": "#1042"}
text = template
for old, new in values.items():
text = text.replace(old, new)
print(text) # Dear Ana, your order #1042 shipped.Notice that text is reassigned on each pass. Each call works on the output of the previous one.
Order matters
Each replace sees the result of the one before it, so substitutions can interfere with each other. The classic case is trying to swap two values.
s = "a b"
print(s.replace("a", "b").replace("b", "a")) # a aThe first call turns "a b" into "b b". The second call then turns both letters into a. The original distinction is gone. Here are two ways to get a real swap.
s = "a b"
# 1. Use a placeholder that cannot appear in the text
print(s.replace("a", "\0").replace("b", "a").replace("\0", "b")) # b a
# 2. Map both characters in a single pass
print(s.translate(str.maketrans("ab", "ba"))) # b aA placeholder works for longer strings too, but only if you are certain it never occurs in the input. A single-pass tool such as translate does not have this risk.
The same interference can happen with a dictionary loop. If a substituted value contains another key, a later iteration will replace inside it. When values come from users, prefer a tool that substitutes in one pass, such as str.format_map or re.sub with a function.
Substring traps
replace has no idea what a word is. It replaces matching characters wherever they occur, including inside longer words.
text = "cat concatenate cat"
print(text.replace("cat", "dog")) # dog condogenate dogYou can reduce the damage by including surrounding spaces in old, but that fails at the start and end of the string and next to punctuation. For whole-word replacement, regular expressions have word boundaries.
import re
text = "cat concatenate cat"
print(re.sub(r"\bcat\b", "dog", text)) # dog concatenate dogKnowing whether anything changed
replace does not tell you how many replacements it made, or whether it made any. When you need that information, count first or compare afterwards.
s = "a-b-c"
n = s.count("-")
t = s.replace("-", "+")
print(n) # 2
print(t != s) # TrueCounting first and replacing second scans the text twice. For ordinary strings that cost is negligible. If the count must reflect a count limit, use min(s.count(old), limit).
Common errors
- Discarding the result.
s.replace(...)without assignment does nothing useful. Writes = s.replace(...). - Expecting regex behavior.
replacetreatsoldas literal text. In"a.b".replace(".", "-")the dot matches only a real dot, so the result isa-b. No escaping is needed. - Passing a non-string.
"x1".replace("1", 2)raisesTypeError. Convert withstr(2)first. - Assuming replaced text is searched again. It is not, as shown with
"aa".replace("a", "aa"). - Chaining swaps. Sequential replacements can undo each other, as shown above.
Exercise
What does "banana".replace("an", "AN", 1) return, and what does "aaaa".replace("aa", "a") return? Explain the second result in terms of how the scan works.
Show answer
The first call returns "bANana", because only the leftmost match is replaced when count is 1. The second call returns "aa". The scan matches the first two characters and emits a, then skips past them and matches the last two characters and emits another a. Matches do not overlap, and the inserted text is not rescanned, so the result is two characters, not one.
Exercise
Write a function swap(text, x, y) that swaps every occurrence of the single characters x and y in text, without using a placeholder character. Show the result for swap("a1b2a", "a", "b").
Show answer
Use a single translation table so both mappings apply in one pass:
def swap(text, x, y):
return text.translate(str.maketrans(x + y, y + x))
print(swap("a1b2a", "a", "b")) # b1a2b
Chained replace calls would turn every character into the same letter. translate maps each character once, so the two substitutions cannot interfere.