1

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

2

2 Answers 2

6

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
0
4

You can do this in a clever one-liner with string.replace().

  1. Reverse the string
  2. Replace all 'aa' with 'd'. This normally creates a problem because the replacement happens at every first instance of 'aa', so 'aaa' would become 'da' rather than our desired 'ad'. However, we reversed the string.
  3. Reverse the string again to put it back in original order
  4. Replace all 'a' with 'c'. Since we replace all 'aa' with 'd', there are only single 'a' left.

The code is therefore: my_string = my_string[::-1].replace('aa', 'd')[::-1].replace('a', 'c').

1
  • This is short, fast and easy to cope with. As much as I like @anuvhava's solution and love regex in general, this solution looks to be underrated. Commented Apr 5, 2024 at 16:26

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.