liveBook · Manning

Sub

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

re.sub() is a Python regular-expression function that returns text with matches of a pattern replaced by specified replacement text.

re.sub() replaces text matching a regular-expression pattern and returns a new string, leaving the original string unchanged. section 8.3.2 section 8.6

Replace lowercase and uppercase vowels

import re text = 'Apples and Bananas!' vowel = 'o' text = re.sub('[aeiou]', vowel, text) text = re.sub('[AEIOU]', vowel.upper(), text) print(text) # Opplos ond Bononos! section 8.3.2

The call follows a compact pattern:

  • Pass the pattern to search, the replacement text, and the input string. section 17.1.4
  • Use a character class such as [aeiou] when any listed character should match. section 8.3.2
  • By default, replace every leftmost, non-overlapping match; count and flags can also be supplied. section 17.1.4
  • Replace placeholders such as <noun> with supplied values, or remove unwanted characters with an empty replacement. section 17.1.4 section 18.3.1
sub(pattern, repl, string, count=0, flags=0)
   Return the string obtained by replacing the leftmost
   non-overlapping occurrences of the pattern in string by the
   replacement repl.

Use the signature as a quick reference for arguments and the default replacement behavior. section 17.1.4

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines the call signature and demonstrates character classes, sequential replacements, and empty-string filtering without explaining regex engine internals.
Examples
Demonstrates vowel conversion, Mad Libs placeholders, and removing punctuation before ASCII-based word scoring.
What it assumes
Assumes basic Python strings and functions while introducing regular-expression syntax through small replacement tasks.
What you can do after
Apply it via Python's re module to perform pattern-based substitutions and preserve the unchanged input string.
How it connects
Connects regular expressions with character classes, re.findall(), string replacement, map(), and ASCII character ranges.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.