Python 在找到匹配项后增加整数
我有一篇关于网站的文章,比如说“www.test.com”。我想用“website_NR”替换所有这些事件,其中NR应该从1开始 例如:Python 在找到匹配项后增加整数,python,regex,Python,Regex,我有一篇关于网站的文章,比如说“www.test.com”。我想用“website_NR”替换所有这些事件,其中NR应该从1开始 例如: text = "bbsjsddh www.test.com shduh sudhuhd sjdjsdh wiowqiuedl www.test.de uasuisdhckjdfh www.test.de sudhdhdhfh" 现在,每次出现的“www.test.com”都应该被“website\u 1”、“website\u 2”等所取代 我试了一下: n
text = "bbsjsddh www.test.com shduh sudhuhd sjdjsdh wiowqiuedl www.test.de uasuisdhckjdfh www.test.de sudhdhdhfh"
现在,每次出现的“www.test.com”都应该被“website\u 1”、“website\u 2”等所取代
我试了一下:
n = 0
if 'www.test.com' in text:
n = n+1
text = text.replace('www.test.com', 'website_'+str(n))
但是…此方法只计算第一次出现的“www.test.com”下面的代码函数将用
new+'{}替换old
。当old
在字符串中时,格式(n)
一次一个。它也会在每次迭代中增加n
,因此您会得到“website\u 1”、“website\u 2”等
def func(s, old, new):
n = 1
while old in s:
s = s.replace(old, new + '_{}'.format(n), 1)
n += 1
return s
text = "bbsjsddh www.test.com shduh sudhuhd sjdjsdh wiowqiuedl www.test.com uasuisdhckjdfh www.test.com sudhdhdhfh"
print(func(text, 'www.test.com', 'website'))
# bbsjsddh website_1 shduh sudhuhd sjdjsdh wiowqiuedl website_2 uasuisdhckjdfh website_3 sudhdhdhfh
好。。。如果您想不止一次地执行某项操作,则需要编写一个循环。.count给出出现次数(n),然后替换n次