0

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']
ekhumoro
  • 115,249
  • 20
  • 229
  • 336
  • 3
    Please take some time reading about how to create a [Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – Vasilis G. Dec 01 '17 at 01:52
  • `[int(t) for t in tokens if t.isdigit() else t]` – Nir Alfasi Dec 01 '17 at 01:55
  • @alfasin `isdigit` will fail negative numbers – Patrick Haugh Dec 01 '17 at 01:57
  • Possible duplicate of [Python: Check if a string represents an int, Without using Try/Except?](https://stackoverflow.com/questions/1265665/python-check-if-a-string-represents-an-int-without-using-try-except) – Tom Karzes Dec 01 '17 at 01:59
  • @PatrickHaugh you're right: `[int(t) for t in tokens if re.match(r'^-?\d+$', t) else t]` – Nir Alfasi Dec 01 '17 at 02:02
  • Possible duplicate of [Python: Extract numbers from a string](https://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string) – robinCTS Dec 01 '17 at 02:44

2 Answers2

1

You need to cast the items in the list to ints 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 != '']
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

Use a for loop without the syntactic sugar. Convert the str of the integers to int using string method isdigit().

Example:

>>> "4".isdigit()
>>> True
jeevaa_v
  • 423
  • 5
  • 14