我想使用 python 从字符串中替换子字符串的交替出现

1 python string

我有一个字符串。我想用新的子字符串替换每个备用子字符串,以便在下面的字符串中第 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)
Run Code Online (Sandbox Code Playgroud)

预期输出: abcrrhghxxjjhrrjjhj

Tim*_*sen 7

我们实际上可以通过一次调用来处理这个re.sub

str1 = "abcxxhghxxjjhxxjjhj"
output = re.sub(r'xx(.*?)(xx|$)', r'rr\1\2', str1)
print(output)  # abcrrhghxxjjhrrjjhj
Run Code Online (Sandbox Code Playgroud)

该战略是寻找xx其次是最近的xx,然后更换一次xxrr,单独留下剩余的内容。以下是正则表达式模式的解释:

xx      match 'xx'
(.*?)   match and capture all content up until
(xx|$)  the nearest next 'xx' OR the end of the input
Run Code Online (Sandbox Code Playgroud)

然后,我们替换为rr\1\2,仅将前导更改xxrr