Name
sub
Synopsis
r.sub(repl,s,count=0)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 mo.group(0).upper( ) 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access