Splitting a math expression string into tokens in Python

后端 未结 2 1137
死守一世寂寞
死守一世寂寞 2020-12-20 19:05

I have a lot of python strings such as \"A7*4\", \"Z3+8\", \"B6 / 11\", and I want to split these strings so that they would be in a l

2条回答
  •  天涯浪人
    2020-12-20 19:31

    There is a way to solve this without regular expressions by using the Python tokenizer. I used a more complex formula to show the capabilities of this solution.

    from io import StringIO
    import tokenize
    
    formula = "(A7*4) - (Z3+8) -  ( B6 / 11)"
    print([token[1] for token in tokenize.generate_tokens(StringIO(formula).readline) if token[1]])
    

    Result:

    ['(', 'A7', '*', '4', ')', '-', '(', 'Z3', '+', '8', ')', '-', '(', 'B6', '/', '11', ')']
    

提交回复
热议问题