5. Substitute
re.sub() replaces matches with new text and returns a new string:
pattern— the regex to find.replacement— the text that replaces each match.string— the original text; it is not changed, because strings are immutable.count— optional; pass it by name ascount=1. Default0replaces all matches;count=1replaces only the first.flags— optional, same flags assearchandfindall, for examplere.IGNORECASE.
The replacement can refer to captured groups: \1 is the text of group 1, \2 is group 2, and so on. Use a raw string for the replacement so \1 reaches re intact:
Coming from JavaScript? re.sub is text.replace(regex, replacement), but Python replaces every match by default. JS replace with a string pattern replaces only the first and needs replaceAll or a /g regex to replace all.
Replace every match
Import re and call re.sub() with the pattern "cat", the replacement "dog" and the text "cat cat cat". Print the new string.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Replace only the first match
Use the same pattern, replacement and text, but pass count=1 to re.sub(). Only the first cat is replaced.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Replace ignoring case
re.sub() accepts the same flags as the other functions. Replace "cat" with "dog" in "Cat cat CAT" using flags=re.IGNORECASE. All three spellings match.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Reorder with groups
Use the pattern r"(Ada) (Lovelace)" on "Ada Lovelace". Make the replacement the raw string r"\2, \1": group 2, a comma and a space, then group 1. Print the new string.
Print exactly:
Create a free account to save your progress and unlock chapter 2.