深度阅读

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

作者
作者
2023年08月22日
更新时间
9.79 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。