How to replace a substring in Python
Use str.replace(old, new, count) to replace all occurrences or limit replacements in a single call.
def replace_substring(text: str, old: str, new: str, count: int | None = None) -> str:
"""Replace old with new; if count is None replace all."""
return text.replace(old, new, count) if count is not None else text.replace(old, new)
# example
s = "foo bar foo"
print(replace_substring(s, "foo", "baz"))The snippet defines replace_substring, which forwards its arguments to the built‑in str.replace method. If count is supplied, only that many left‑most occurrences are changed; otherwise all matches are replaced. The function returns the new string without mutating the original, fitting Python's immutable string model.
Using str.replace is O(n) and runs in C, so it is faster and less error‑prone than manual loops or regex when you only need literal substitution. Beware that replace works on exact substrings; overlapping patterns are not handled, and count must be a non‑negative integer if used. For pattern‑based needs switch to re.sub.
Variations
Regex based replacement
import re
def replace_regex(text, pattern, repl, count=0):
"""Replace pattern using regex; count=0 means replace all."""
return re.sub(pattern, repl, text, count=count)Use when you need pattern matching; slower than str.replace and requires careful escaping.
File content replacement (atomic)
from pathlib import Path
def replace_in_file(path: Path, old: str, new: str):
text = path.read_text()
path.write_text(text.replace(old, new))Safe for small to medium files; writes whole file at once.
Replace only first N occurrences
def replace_n(text: str, old: str, new: str, n: int):
return text.replace(old, new, n)Pass n to limit replacements; n must be >=0.
Get one Python lesson + one career idea every Friday
No spam, no "buy our course now". Three bullets, every Friday. Unsubscribe with one click.