Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split an expression string to a list in Python?

Tags:

python

regex

I'm new to Python and I'm trying to create some kind of a calculator that reads expressions as strings and calculates them (without eval). In order to do so I'm working with a list after converting the string to a list separated by parentheses, operators and values. I have a list that contains the operators too, I just don't know how to use it in the regex split so up until now I've done that manually.

I have 3 issues with my code:

  1. The code doesn't split correctly negative numbers.
  2. The code doesn't allow to add operators (in example - if I'd like to add _ as a new operator in the future, the code won't know to split according to it).
  3. The code brings back numbers as strings, which I then convert to integers in an outside function.
    # Removing any unwanted white spaces, tabs, or new lines from the equation string:
    equation = re.sub(r"[\n\t\s]*", "", equation)
    # Creating a list based on the equation string:
    result_list = re.split(r'([-+*/^~%!@$&()])|\s+', equation)
    # Filtering the list - Removing all the unwanted "spaces" from the list:
    result_list = [value for value in result_list if value not in ['', ' ', '\t']]

For example: 5--5 -> I'd like to get: [5, '-', -5] -> I currently get: ['5', '-', '-', '5']

Another example : ((500-4)*-3) -> I'd like to get: ['(', '(', 500, '-', '4', ')', *', '-3', ')']

like image 470
RnadomG Avatar asked Nov 18 '25 13:11

RnadomG


1 Answers

Here is a way to go:

import re

arr = [
    '5--5',
    '((500-4)*-3)',
]

for s in arr:
    res = re.findall(r'\b-\b|-?\d+|\D', s)
    print res

Output:

['5', '-', '-5']
['(', '(', '500', '-', '4', ')', '*', '-3', ')']

Demo & explanation

like image 138
Toto Avatar answered Nov 20 '25 03:11

Toto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!