0

I am trying to reverse all substrings that are in parentheses within a string. this post (Reverse marked substrings in a string) showed me how to do that (I am using the first answer), but I am having a problem with parentheses within parentheses. The code is currently not working with multiple layers of parentheses. For example the string 'ford (p(re)fe)ct', should return as 'ford efrepct', but is instead returning as 'ford er(pfe)ct'. (It should reverse the content of each parentheses in relation to its parent element).

here is my code:

def reverseInParentheses(iss):
    import re
    new = re.sub('\((.*?)\)', lambda m: m.group(1)[::-1], iss)

    print(new)

thanks!

2 Answers2

0

One simple and naive approach to fix this: exclude opening parentheses within your matching group and just repeat until there are no more parentheses.

import re

def reverseInParentheses(iss):
    while '(' in iss:    
        iss = re.sub('\(([^\(]*?)\)', lambda m: m.group(1)[::-1], iss)
    return iss

print(reverseInParentheses('ford (p(re)fe)ct'))
# ford efrepct
user2390182
  • 72,016
  • 6
  • 67
  • 89
0

Here's my solution without using regular expressions. Maybe it can be written more compact by using list comprehension or even using recursion - but I think this is weird enough ;)

def reverse_in_parenthesis(str0):
    separators = ['(', ')']
    for separator in separators:
        if not separator in str0:
            return str0

    str1 = str0.split('(')      # ['ford ', 'p', 're)fe)ct']
    str2 = str1[-1].split(')')  # ['re', 'fe', 'ct']

    res = str1[0]  # everything before 1st '(' remains as is
    for i,s in enumerate(str2[:-1][::-1]):
        res = ''.join((res, s if i%2 else s[::-1]))
    for i,s in enumerate(str1[1:-1][::-1]):
        res = ''.join((res, s if i%2 else s[::-1]))
    res = ''.join((res, str2[-1]))  # everything after last ')' remains as is
    return res

print(reverse_in_parenthesis('ford (p(re)fe)ct'))

Output:

ford efrepct
AcK
  • 2,063
  • 2
  • 20
  • 27