Returns a copy of s where non-overlapping matches with r are replaced by repl, which can be either a string or a callable object, such as a function. An empty match is replaced only when not adjacent to the previous match. When count is greater than 0, only the first count matches of r within s are replaced. When count equals 0, all matches of r within s are replaced. For example, here’s another way to remove only the first occurrence of substring 'hello' in any mix of cases:

import re
rehello = re.compile(r'hello', re.IGNORECASE)
astring = rehello.sub('', astring, 1)

Without the final 1 argument to method sub, this example would remove all occurrences of 'hello‘.

When repl is a callable object, repl must accept a single argument (a match object) and return a string to use as the replacement for the match. In this case, sub calls repl, with a suitable match-object argument, for each match with r that sub is replacing. For example, to uppercase all occurrences of words starting with 'h' and ending with 'o' in any mix of cases, you can use the following:

import re
h_word = re.compile(r'\bh\w+o\b', re.IGNORECASE)
def up(mo): return )
astring = h_word.sub(up, astring)

Method sub is a good way to get a callback to a callable you supply for every non-overlapping match of r in s, without an explicit loop, even when you don’t need to perform any substitution. The following example shows this by using the sub method to build a function ...

Get Python in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.