Python 的 re.subn() 方法类似于 re.sub() 方法,但它会返回修改后的字符串和替换的计数。它使用正则表达式模式对字符串执行搜索和替换操作。将返回带有替换项的修改字符串以及替换计数。
当我们需要知道除了获取修改后的字符串之外还进行了多少次替换时,此方法非常有用。当我们需要修改后的字符串和替换计数进行进一步处理时,通常会使用此方法。
语法
以下是 Python re.subn() 方法的语法和参数 -
re.subn(pattern, repl, string, count=0, flags=0)
参数
以下是 python re.subn() 方法的参数 -
- pattern:要搜索的正则表达式模式。
- repl:要为每个匹配项调用的替换字符串或函数。
- string:要对其执行替换的输入字符串。
- count(可选):要进行的最大替换数。默认值为 0,表示替换所有匹配项。
- flags(可选):用于修改匹配行为的标志(例如,re.IGNORECASE 的)
返回值
此方法返回 match 对象和替换数的迭代器。
示例 1以下是 python re.subn() 方法的基本示例,其中字符串中的所有数字序列都替换为字符串 'number',并且还返回替换的计数 -
import re
result, count = re.subn(r'\d+', 'number', 'There are 123 apples and 456 oranges.')
print(result)
print(count)
输出
There are number apples and number oranges.
2
2
示例 2
此示例使用 pattern 和 replacement 字符串中的捕获组来重新排列日期格式。这里只进行了一次替换,因此 count 为 1。
import re
result, count = re.subn(r'(\d+)-(\d+)-(\d+)', r'\3/\2/\1', 'Date: 2022-01-01')
print(result)
print(count)
输出
Date: 01/01/2022
1
1
示例 3
在此示例中,使用函数 square 作为替换。它将字符串中找到的每个数字匹配项平方,返回替换计数 5 −
import re
def square(match):
num = int(match.group())
return str(num ** 2)
result, count = re.subn(r'\d+', square, 'Numbers: 1 2 3 4 5')
print(result)
print(count)
输出
Numbers: 1 4 9 16 25
5
5