Sub topic 8
Replacing text
This chapter assumes you know basic Python syntax, can call methods on a str, and understand that strings are immutable. You will use str.replace to substitute text, limit how many substitutions happen, and avoid a few common mistakes.
How replace works
str.replace(old, new, count=-1) returns a copy of the string in which occurrences of old are replaced by new. By default it replaces every occurrence, scanning from left to right.
print("a-b-c".replace("-", "+")) # a+b+c
print("a-b-c".replace("-", "+", 1)) # a+b-c| Argument | Meaning |
|---|---|
| `old` | The exact text to look for. It is not a pattern. |
| `new` | The text to put in its place. It can be an empty string. |
| `count` | The maximum number of replacements. A negative value, the default, means no limit. |
replace matches exact text and is case-sensitive. "Cat".replace("cat", "dog") returns "Cat" unchanged.
Keep the result
Like every str method, replace returns a new string and leaves the original alone. A common bug is calling it and discarding the result.
title = "draft report"
title.replace("draft", "final")
print(title) # draft report
title = title.replace("draft", "final")
print(title) # final reportIf the substring is missing, replace does not raise an error. It returns a string equal to the original. To find out whether anything changed, compare the result with the input or test with in first.
Deleting text
Pass an empty string as new to delete text.
phone = "555-123-4567"
print(phone.replace("-", "")) # 5551234567Do not pass an empty string as old. Python treats it as matching between every character, and at both ends.
print("abc".replace("", "-")) # -a-b-c-Replacements happen in sequence
Each replace call works on the output of the previous one. This breaks attempts to swap two values.
text = "abba"
print(text.replace("a", "b").replace("b", "a")) # aaaaThe first call turns the string into bbbb, so the second call has no way to tell the original letters apart. str.translate makes all substitutions in one pass, so it handles swaps correctly.
swap = str.maketrans("ab", "ba")
print("abba".translate(swap)) # baabUse translate when you map single characters to other characters. Use replace when you work with longer pieces of text.
Matches inside larger words
replace has no idea where words begin or end. It changes every occurrence of the text, including those inside other words.
print("cat catalog".replace("cat", "dog")) # dog dogalogYou can shrink the problem by including surrounding spaces in old, but that fails at the start or end of a string and next to punctuation. If you need whole-word matching, use the re module with a word boundary, as a later chapter explains.
A small cleanup example
Several replace calls can be chained when the replacements do not interfere with each other.
def slugify(title):
return title.strip().lower().replace(" ", "-").replace("_", "-")
print(slugify(" My_First Post ")) # my-first-postHere lower runs first, so the later replacements never need to care about case.
Common errors
- Forgetting to assign the result, so the original value is used afterward.
- Expecting
replaceto be case-insensitive or to accept a pattern such as"\d+". - Chaining replacements whose output feeds the next one, as in the swap example.
- Using an empty
oldstring by accident, for example when a variable is unexpectedly blank.
Exercise
What does "banana".replace("an", "AN", 1) return, and what does "banana".replace("x", "y") return?
Show answer
The first call returns "bANana", because count=1 stops after the first match. The second call returns "banana" unchanged, because replace does not raise an error when the substring is missing.
Exercise
Why does "abba".replace("a", "b").replace("b", "a") fail to swap the letters, and what is a better approach?
Show answer
The second call also sees the b characters created by the first call, so everything ends up as "aaaa". Use str.translate with str.maketrans("ab", "ba"), which substitutes all characters in a single pass and returns "baab".