Reputation: 11
I have a string. I want to replace every alternate substring with a new substring so that in the below string 1st and 3rd occurrences of xx
should change to 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)
Expected output : abcrrhghxxjjhrrjjhj
Upvotes: 1
Views: 88
Reputation: 817
this should work:
for i in re.finditer("xx",str1):
cnt=cnt+1
if cnt%2!=0:
str1 = str1[:i.start()] + "rr" + str1[i.start() + 2:]
slicing the string with the re.finditer index
Upvotes: 0
Reputation: 520948
We can actually handle this with a single call to re.sub
:
str1 = "abcxxhghxxjjhxxjjhj"
output = re.sub(r'xx(.*?)(xx|$)', r'rr\1\2', str1)
print(output) # abcrrhghxxjjhrrjjhj
The strategy is to find xx
followed by the nearest xx
, then replace the first xx
with rr
, leaving the remaining content alone. Here is an explanation of the regex pattern:
xx match 'xx'
(.*?) match and capture all content up until
(xx|$) the nearest next 'xx' OR the end of the input
Then, we replace with rr\1\2
, changing only the leading xx
into an rr
.
Upvotes: 7