Replace matching substrings with a new string for all occurrences, or a specified number.
re.sub(<pattern>, <replacement>, string, <count>, <flags>)
<pattern> is a regular expression that can include any of the following:
- A string:
- A character class code:
- A regex symbol:
The other arguments include:
- The replacement string (
- An integer value for the number of replacements (
The following example replaces all occurrences of “BI” with “business intelligence”:
import reblurb = '''The analytics firm uses a range of BI tools to visualize data. Their internal data science team suggestsbi tools may be their most valuable resource.'''match = re.sub(r'bi','business intelligence',blurb,flags=re.IGNORECASE)# The ignorecase flag allows for matches regardless of caseprint(match)
This will print the following where “bi” is replaced with “business intelligence”:
The analytics firm uses a range of business intelligence tools to visualize data. Their internal data science team suggestsbusiness intelligence tools may be their most valuable resource.
Replace all numerical values with “REDACTED”:
Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.
Learn Python on Codecademy
Computer ScienceLooking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
Includes 6 Courses
With Professional Certification