Sub topic 14
When string methods are not enough
This chapter assumes you know the str methods from earlier chapters (find, replace, split, strip) and can read basic Python. It shows where those methods stop working and when to use the re module instead.
What string methods cannot express
Every method you have used matches literal text. replace("cat", "dog") looks for the exact characters c, a, t. It cannot ask for "a whole word", "three digits in a row", or "either a comma or a semicolon".
Here is the most common failure:
text = "The cat sat on the concatenated category."
print(text.replace("cat", "dog"))The output is The dog sat on the condogenated dogegory. The method replaced every occurrence of the characters, including those inside other words.
Regular expressions in brief
A regular expression (regex) is a pattern that describes a set of strings. Python's re module applies patterns to text. Write patterns as raw strings (r"...") so backslashes reach re unchanged.
import re
text = "The cat sat on the concatenated category."
print(re.sub(r"\bcat\b", "dog", text))The output is The dog sat on the concatenated category. Here \b matches a word boundary, the point between a word character and a non-word character. Only the standalone word cat matches.
Common patterns that need re
The next example shows three cases where a plain method has no equivalent.
import re
print(re.findall(r"\d{3}-\d{4}", "Call 555-1234 or 555-9876."))
# ['555-1234', '555-9876']
print(re.split(r"[,;]\s*", "a, b;c, d"))
# ['a', 'b', 'c', 'd']
print(len(re.findall(r"(?=aa)", "aaaa")))
# 3\d{3}-\d{4}means three digits, a hyphen, then four digits.[,;]\s*means one comma or semicolon followed by any amount of whitespace.str.splitaccepts only one literal separator.(?=aa)is a lookahead. It checks foraawithout consuming it, so overlapping matches are counted. This gives 3, where"aaaa".count("aa")gives 2.
Choosing the right tool
| Task | String method | Needs `re` |
|---|---|---|
| Is `"abc"` in the text? | `in` | No |
| Does it end in `.csv` or `.tsv`? | `endswith` with a tuple | No |
| Replace one literal | `replace` | No |
| Replace a whole word only | None | Yes |
| Split on several separators | None | Yes |
| Match a shape such as dates or ZIP codes | None | Yes |
Common errors
- Forgetting the raw string. In
"\bcat\b", Python reads\bas a backspace character. Writer"\bcat\b". - Using
re.matchwhen you meanre.search.matchonly tests the start of the string.searchscans the whole string. - Parsing nested or recursive formats. Regex is a poor fit for HTML, JSON, or source code. Use a real parser for those.
- Overbuilding. A pattern you cannot read next week costs more than three chained string methods.
Exercise
You need to replace the word "is" with "was" in "This island is small", without changing "This" or "island". Why does replace fail here, and what call fixes it?
Show answer
"This island is small".replace("is", "was") replaces the characters is inside "This" and "island" too. Use re.sub(r"\bis\b", "was", "This island is small"), which returns This island was small, because \b limits the match to the standalone word.