Reputation: 1
I tried:
tokens = [t.strip() for t in re.split(r'((?:-?\d+)|[+\-*/()])', exp)]
return [t for t in tokens if t != '']
But it gets the wrong result:
Expected :[3, '+', -4, '*', 5]
Actual :['3', '+', '-4', '*', '5']
Upvotes: 0
Views: 106
Reputation: 60974
You need to cast the items in the list
to int
s where appropriate
def try_int(s):
try:
return int(s)
except ValueError:
return s
Then in your function, you can apply this to all the items in the return list
return [try_int(t) for t in tokens if t != '']
Upvotes: 1
Reputation: 423
Use a for loop without the syntactic sugar. Convert the str of the integers to int using string method isdigit()
.
Example:
>>> "4".isdigit()
>>> True
Upvotes: 0