Search code examples
pythonregexstringif-statementreplace

conditional replace of a string in python


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


Solution

  • Here is a regex based solution that avoids 2 times reversing:

    import re
    string = "abaabaaabaaaabaaabaaaaaabaababaaabaaaabaaaaaabaaaaabaaabaabaababaaabaaaabaaaabaabaaab"
    
    print (re.sub(r'(?<!a)a(?=(?:aa)*(?!a))', 'c', string).replace('aa', 'd'))
    

    Output:

    cbdbcdbddbcdbdddbdbcbcdbddbdddbcddbcdbdbdbcbcdbddbddbdbcdb
    

    RegEx Demo

    RegEx Details:

    • (?<!a): Assert that previous character is not a
    • a: Match single a
    • (?=(?:aa)*(?!a)): Assert that we have 0 or more double a characters ahead that are not followed by another a