Python re.sub()
Anonymous contributor
Published Jul 30, 2021Updated Oct 14, 2024
Contribute to Docs
The re.sub() function replaces matching substrings with a new string for all occurrences, or a specified number.
Syntax
re.sub(<pattern>, <replacement>, string, <count>, <flags>)
<pattern>: A regular expression pattern used to match substrings.- A string:
Jane Smith - Character class codes:
/w,/s,/d - Regex symbols:
$,|,^
- A string:
<replacement>: The replacement argument. This can either be a string or a function.<count>: An integer specifying the number of occurrences to replace. The default is to replace all matches.<flags>: Specifies additional options such asIGNORECASE,VERBOSE,DOTALL, etc.
Example
The following example replaces all occurrences of “BI” with “business intelligence”:
import redef replace_business_intelligence(match):return 'business intelligence'blurb = '''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.'''# Use the function `replace_bussines_intelligence` as the replacement argument in re.sub()match = re.sub(r'bi', replace_business_intelligence, blurb, flags=re.IGNORECASE)print(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.
Codebyte Example
Replace all numerical values with “REDACTED”:
All contributors
- Anonymous contributor
- Anonymous contributor
- rrayhka
- Anonymous contributor
BrandonDusch- StevenSwiniarski
christian.dinh
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Get a taste of regular expressions (regex), a powerful search pattern language to quickly find the text you're looking for.
- Beginner Friendly.1 hour