我想使用python从字符串中替换子字符串的交替出现
我有一个字符串。我想用新的子字符串替换每个备用子字符串,以便在下面的字符串中第 1 次和第 3 次出现的xx应该更改为rr.
#------------------------------------------------------
import re
str1="abcxxhghxxjjhxxjjhj"
cnt=0
for i in re.finditer("xx",str1):
cnt=cnt+1
if cnt%2!=0:
print(cnt)
l=i.span()[0]
m=i.span()[1]
print(l,m)
str1=re.sub(str1[l:m],"rr",str1)
print(str1)
预期输出: abcrrhghxxjjhrrjjhj
回答
我们实际上可以通过一次调用来处理这个re.sub:
str1 = "abcxxhghxxjjhxxjjhj"
output = re.sub(r'xx(.*?)(xx|$)', r'rr12', str1)
print(output) # abcrrhghxxjjhrrjjhj
该战略是寻找xx其次是最近的xx,然后更换一次xx用rr,单独留下剩余的内容。以下是正则表达式模式的解释:
xx match 'xx'
(.*?) match and capture all content up until
(xx|$) the nearest next 'xx' OR the end of the input
然后,我们替换为rr12,仅将前导更改xx为rr。