Python
string manipulation
regular expressions
replace method
programming tips

Python string.replace regular expression

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

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.

python
1text = "cat cot cut"
2
3print(text.replace("cat", "dog"))
4print(text.replace("c.t", "dog"))

Output:

text
dog cot cut
cat cot cut

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.

python
1import re
2
3text = "cat cot cut"
4result = re.sub(r"c.t", "dog", text)
5
6print(result)

This prints dog dog dog because the pattern matches all three words.

The basic mental model is:

  • 'str.replace is for fixed substrings'
  • 're.sub is 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.

python
path = "docs/readme.txt"
print(path.replace(".txt", ".md"))

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:

python
1import re
2
3text = "one   two\t\tthree\nfour"
4print(re.sub(r"\s+", " ", text))

Remove all digits:

python
1import re
2
3text = "Order A-123-B"
4print(re.sub(r"\d+", "", text))

Replace only a suffix at the end of the string:

python
1import re
2
3filename = "report.csv"
4print(re.sub(r"\.csv$", ".json", filename))

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.

python
1import re
2
3text = "2026-03-07"
4result = re.sub(r"(\d{4})-(\d{2})-(\d{2})", r"\3/\2/\1", text)
5
6print(result)

This prints 07/03/2026.

You can also use a function as the replacement when the new value depends on the match:

python
1import re
2
3def double_number(match):
4    return str(int(match.group(0)) * 2)
5
6
7text = "A1 B20 C300"
8print(re.sub(r"\d+", double_number, text))

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.

python
1import re
2
3text = "abc123"
4print(re.sub(r"\d+", "#", text))

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.

python
1import re
2
3pattern = re.compile(r"\s+")
4
5lines = ["a   b", "c\t d", "e\nf"]
6for line in lines:
7    print(pattern.sub(" ", line))

This improves readability and can reduce repeated parsing overhead in hot paths.

Common Pitfalls

  • Expecting str.replace to 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.replace performs literal replacement only.'
  • Use re.sub when 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.sub much more flexible than replace.
  • Prefer raw strings for regex patterns so they stay readable and correct.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track 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.

Browse interview questions

All Rights Reserved.