python .replace regex
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
In Python, str.replace does not understand regular expressions. It only replaces exact literal text. If you need pattern matching, capture groups, or conditional replacement logic, the correct tool is re.sub. Most confusion on this topic comes from trying to use replace with a regex pattern string and expecting regex behavior.
str.replace Versus re.sub
Use str.replace when the input is literal and fixed.
That works because Order- is exact text. No pattern matching is needed.
If you need to match variable content, use re.sub.
Here the pattern captures the digits and reuses them in the replacement. str.replace cannot do that.
Use Raw Strings for Regex Patterns
Python string escaping and regex escaping interact in confusing ways. Raw strings reduce that confusion.
The r prefix means backslashes are passed to the regex engine more directly. Without raw strings, patterns with boundaries, escapes, or backreferences are easier to get wrong.
Replacing With Capture Groups
Regex replacement becomes especially useful when only part of the matched text should change.
This pattern keeps the dynamic name while changing the label from user to member.
Capture groups also help with cleanup problems such as repeated words.
That removes adjacent duplicates while preserving one copy.
Use a Function for Dynamic Replacement Logic
When the replacement depends on calculation or branching, pass a function to re.sub.
This is clearer than building increasingly complex replacement strings and is usually easier to test.
Precompile Patterns for Repeated Use
If the same pattern runs many times, compile it once.
Precompiling matters more in loops, services, and data pipelines than in small one-off scripts.
Know the Limits of Regex Replacement
Regex is powerful, but it is not the right answer for every structured format. For example, replacing parts of HTML, JSON, or CSV with regex often creates brittle code. If the text has a real grammar, use a parser or a format-specific library instead of forcing everything through pattern substitution.
That rule matters because re.sub can make a quick one-line solution feel correct even when the actual input format is more complicated than a regex should handle.
Common Pitfalls
The first mistake is trying to pass a regex to str.replace. It treats the pattern as plain text, so nothing special happens.
Another common issue is forgetting raw strings. Backslashes that were meant for the regex engine may be interpreted by Python first.
Greedy patterns are also dangerous. A pattern such as .* can consume more text than intended. Use more specific character classes or non-greedy quantifiers when necessary.
Finally, be careful with backreferences in replacement strings. If the replacement logic becomes hard to read, switch to a replacement function instead of making the regex more cryptic.
Summary
- Use
str.replacefor literal text replacements only. - Use
re.subwhen you need regex pattern matching. - Prefer raw strings for regex patterns and replacements.
- Use capture groups or replacement functions for structured changes.
- Do not use regex when the input format really needs a parser.
Related reading
- Python Request Post with param data
- Python Requests - No connection adapters
- Python requests - print entire http request raw?
- Python requests - threads/processes vs. IO
- Python Requests throwing SSLError
- Python re.sub group number after number
- Python retrieve several URLs via select.epoll
- python return, return None, and no return at all -- is there any difference?
.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.