Because of C++ code snippets not dealing with multiple +- in sequence (or even negative number) in expressions, I post this, as it is so much easier for me than C/C++.

EDIT: Fixed signs together with '(' issues and '+' at beginning removing without lstrip, removed separate now unused '(' branch from if. Changed name of prev to plusminus.

Edited 4 Years Ago by pyTony

""" Expression cleanup from spaces and multiple +- """

expr = "--4-+--4--  - - ++-++ ( ++  +-- 4* 6.5 / 4.3e6 )- -  -6"
plusminus = new_expr = ''
for c in expr:
    if c.isdigit() or c == '(':
        # do not put + in front of expression or inside ( in front of first expression
        new_expr += c if plusminus == '+' and  (not new_expr or new_expr.endswith('(')) else plusminus + c
        plusminus = ''
    elif c in '+-':
        plusminus = '-' if (c == '-' and plusminus != '-') or (c=='+' and plusminus =='-') else '+'
    elif c != ' ':
        new_expr += c
        if plusminus:
            raise ValueError("+- not in front of number or '('!")
                    
if plusminus:
    raise ValueError("Sign at end of expression!")
else:
    print("%s\n%s" % (expr, new_expr))
    assert eval(expr) == eval(new_expr)

"""Output:
--4-+--4--  - - ++-++ ( ++  +-- 4* 6.5 / 4.3e6 )- -  -6
4-4-(4*6.5/4.3e6)-6
"""

Specialties:
IT/Science/Contracts/Religious translation/interpreting FIN-ENG-FIN
Python programming

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.