Search code examples
pythonregexpython-3.xmultiplicationparentheses

Insert multiplication sign between parenthesis


Suppose you have the following string:

5+5(5)

I want to insert a multiplication sign between the 5 and (5)

5+5*(5)

Now also suppose you have the following other possibility:

5+(5)(5)

I want to insert a multiplication sign between the (5) and (5)

5+(5)*(5)

My attempt:

import re

ex1 = '4+6.9(39.3)(-2.3)(5+4)'

def convert(string):

  return re.sub(r"((?:\d+)|(?:[a-zA-Z]\w*\(\w+\)))((?:[a-zA-Z]\w*)|\()", r"\1*\2", string)

print(convert(ex1))

4+6.9*(39.3)(-2.3)(5+4)

This code only adds a multiplication to the first instance.

If the string is:

ex2 = '5(5)+5(5)+5(5)'

5*(5)+5*(5)+5*(5)

The code works for numbers before a parenthesis.

How can I modify the code to include closed parenthesis before an open one?


Solution

  • You can use positive lookbehind:

    import re
    
    a = '4+6.9(39.3)(-2.3)(5+4)'
    
    print(re.sub('(?<=\d|\))(\()', '*(', a))
    #4+6.9*(39.3)*(-2.3)*(5+4)