I want to perform conditional replace of string. if my
string = "abaabaaabaaaabaaabaaaaaabaababaaabaaaabaaaaaabaaaaabaaabaabaababaaabaaaabaaaabaabaaab"
and I want to replace a with 2 different character, so I want to change single "a" with "c" (a = c) and double "aa" will be with "d" "aa = d", replacement criteria is if odd number of "a" then first with single "a" will replace with "c", then every 2 "a" with "d", for example "ab = cb", "aab = db", "aaab = cdb" (first a = c and next 2 aa with d) aaaab = ddb. after replacement my string will be
"cbdbcdbddbcdbdddbdbcbcdbddbdddbcddbcdbdbdbcbcdbddbddbdbcdb"
Can someone guide me how to write code what I can use "if else" or regex
(?r)
reverse flag, anubhava's solution could be simplified on the regex-side to something likeregex.sub(r'(?r)aa', 'd', string).replace('a', 'c')
regex.sub(r'(?r)aa|(a)', lambda m: 'c' if m[1] else 'd', string)