Python string.replace regular expression
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python's str.replace does not understand regular expressions. It performs literal substring replacement only. If you want pattern-based replacement, the correct tool is re.sub, not replace.
What str.replace Actually Does
str.replace(old, new) looks for exact text matches. It does not treat old as a pattern.
Output:
The second call does nothing because "c.t" is treated as plain text, not as "c followed by any character followed by t."
Use re.sub for Regular Expressions
When the replacement target is a pattern, use the re module.
This prints dog dog dog because the pattern matches all three words.
The basic mental model is:
- '
str.replaceis for fixed substrings' - '
re.subis for pattern matching'
Mixing those up is one of the most common Python text-processing mistakes.
Literal Replacement Is Often Better
Before reaching for regex, ask whether you really need it. Literal replacement is simpler, easier to read, and usually faster when the target string is exact.
That is clearer than a regular expression because there is no pattern ambiguity. Regex is the right tool only when the replacement rule depends on structure rather than exact text.
Common re.sub Patterns
Regular expressions become useful when you need classes of characters, repeated patterns, or anchors.
Replace every run of whitespace with a single space:
Remove all digits:
Replace only a suffix at the end of the string:
These are real regex use cases because the match depends on character classes or position.
Using Capture Groups
re.sub becomes more powerful when you want to preserve part of the matched text. Capture groups let you rearrange or reuse matched sections.
This prints 07/03/2026.
You can also use a function as the replacement when the new value depends on the match:
That pattern is useful when replacement logic is not a fixed string.
Escaping and Raw Strings
Regex patterns often contain backslashes, so Python raw strings are usually the safest way to write them.
Without the r prefix, some patterns become harder to read because Python string escaping and regex escaping overlap.
Also remember that replacement strings have their own escaping rules in regex APIs. If the replacement is literal user text, take care with backslashes.
Compiling Patterns for Reuse
If the same pattern is applied repeatedly, compile it once.
This improves readability and can reduce repeated parsing overhead in hot paths.
Common Pitfalls
- Expecting
str.replaceto interpret regex syntax. It never does. - Using regex when a literal substring replacement would be clearer and simpler.
- Forgetting raw strings for regex patterns, which makes backslashes harder to reason about.
- Writing a regex replacement when only the first occurrence or a fixed suffix matters. Simpler string operations may be enough.
- Confusing the regex pattern with the replacement string. They follow different escaping rules.
Summary
- '
str.replaceperforms literal replacement only.' - Use
re.subwhen the thing being replaced is a pattern. - Reach for regex only when the replacement logic depends on structure, classes, or anchors.
- Capture groups and replacement functions make
re.submuch more flexible thanreplace. - Prefer raw strings for regex patterns so they stay readable and correct.
Related reading
- Python strings and integer concatenation
- python subprocess callback when updated output
- Python subprocess is not scalable by default, any simple solution you can recommend to make it scalable?
- Python subprocess/Popen with a modified environment
- python swapped tuple to dict
- Python synchronous pyaudio data in asynchronous code
- Python SyntaxError EOL while scanning string literal
- Python SyntaxError Non-ASCII character 'xe2' in file
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.