找到事件后增加整数

时间:2014-09-19 12:23:25

标签: 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_1"," website_2"等等......

我尝试过:

n = 0
if 'www.test.com' in text:
        n = n+1
text = text.replace('www.test.com', 'website_'+str(n))

但是......这种方法只计算" www.test.com"

的第一次出现

1 个答案:

答案 0 :(得分:0)

下面的代码函数将old一次替换为new + '_{}'.format(n),而old位于字符串中。每次迭代它也会增加n,因此您可以获得'website_1','website_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