How to use the re.sub() function to substitute matching substrings in a string?

Published on Aug. 22, 2023, 12:18 p.m.

Here’s how to use the re.sub() function to substitute matching substrings in a string using regex:

To replace all occurrences of the pattern with a replacement string, you can use the re.sub() function in Python. re.sub() takes three arguments: a regex pattern, a replacement string, and the target string. For example:

import re

pattern = r'\d+'  # regex pattern to match one or more digits
text = 'I have 3 apples and 2 oranges'
replacement = 'fruit'
new_text = re.sub(pattern, replacement, text)

print(new_text)  # Output: 'I have fruit apples and fruit oranges'

This will replace all non-overlapping occurrences of the regex pattern in the given string with the replacement string. In this case, the regex pattern \d+ matches one or more digits in the text, so the output will be 'I have fruit apples and fruit oranges'.

You can also modify the pattern and replacement strings to match and substitute different types of substrings in the string.

Tags:

re