count = 0
def count_repl(mobj): # --> mobj is of type re.Match
global count
count += 1 # --> count the substitutions
return "your_replacement_string" # --> return the replacement string
text = "The original text" # --> source string
new_text = re.sub(r"pattern", repl=count_repl, string=text) # count and replace the matching occurrences in one pass.
3条答案
按热度按时间kuuvgm7e1#
可以使用
re.subn
。字符串
返回
(new_string, number_of_subs_made)
出于示例目的,我使用了与@Shubham Sharma相同的示例。
型
ggazkfy82#
您可以在调用
re.sub
函数的同时传递repl
函数。* 该函数接受单个匹配对象参数,并返回替换字符串。repl
函数在每次出现非重叠模式时调用。*试试这个:
字符串
或,
你可以使用re.subn,它执行与re.sub相同的操作,但返回一个元组(new_string,number_of_subs_made)。
型
示例:
型
输出:
型
7rtdyuoh3#
字符串
好吧,有个更好的办法
型