C.W.K.
Stream
Lesson 02 of 10 · published

Python re.sub() and re.split()

~10 min · python, substitution, split

Level 0Pattern-Curious
0 XP0/90 lessons0/15 achievements
0/100 XP to next level100 XP to go0% complete

Substitution — the other half of regex

re.sub(pattern, replacement, text) replaces every non-overlapping match of pattern with replacement.

The replacement can be:

  • A literal string: re.sub(r'\d+', 'NUM', 'a 1 b 22 c 333')'a NUM b NUM c NUM'
  • A pattern with backreferences: r'\1' for group 1, r'\g<name>' for named groups, r'\g<0>' for whole match.
  • A callable: receives a Match object, returns a string. Most powerful for dynamic logic.

The count parameter

re.sub(pattern, replacement, text, count=N) replaces only the first N matches. Useful for "only fix the first occurrence" or "don't process more than X."

re.subn — get the count back

re.subn returns a tuple (new_string, num_replacements). Useful when you need to know whether anything changed.

re.split — split with a regex separator

re.split(pattern, text) is like str.split but the separator can be any regex. Splits on every match.

If the pattern contains capture groups, the captured text is INCLUDED in the result list. re.split(r'(\W+)', 'hello, world') returns ['hello', ', ', 'world'] — the separator is preserved.

Code

Substitution and split·python
import re

# Simple substitution
re.sub(r'\d+', 'NUM', 'a 1 b 22 c 333')
# 'a NUM b NUM c NUM'

# Backreference in replacement
re.sub(r'(\d{4})-(\d{2})-(\d{2})', r'\2/\3/\1', '2026-05-04')
# '05/04/2026'

# Named group reference
re.sub(r'(?P<year>\d{4})', r'[\g<year>]', 'born 1989, today 2026')
# 'born [1989], today [2026]'

# Callable replacement — full programmatic control
def bracket_if_large(m):
    n = int(m.group())
    return f'[{n}]' if n > 100 else str(n)

re.sub(r'\d+', bracket_if_large, 'small 5 medium 50 large 500')
# 'small 5 medium 50 large [500]'

# subn returns count
re.subn(r'\d+', 'NUM', 'a 1 b 2')
# ('a NUM b NUM', 2)

# split with regex separator
re.split(r'\W+', 'hello, world! how are you?')
# ['hello', 'world', 'how', 'are', 'you', '']

# split preserving the separator
re.split(r'(\W+)', 'hello, world')
# ['hello', ', ', 'world']

External links

Exercise

Use re.sub with a callable to convert every number in a string to its English word: '5' → 'five', '10' → 'ten'. Use a dict lookup inside the callable. Test on 'I have 3 cats and 7 dogs'.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.