0

if I have a

string = '((a * 5) // ((10 - y) + z))'

and I just want to remove the a, 5, 10, y, z, and put them in

lst1 = []

and I also want to remove the *, -, + and put them in

lst2 = []

What is the best way to do this?

Bach
  • 6,145
  • 7
  • 36
  • 61
user3552506
  • 45
  • 1
  • 1
  • 7
  • In list1 output the `//` should be a single element I assume? – shaktimaan Apr 22 '14 at 23:17
  • I have tried a for loop but it doesn't work for the 10. The for loop works as long as the numbers are between 0 and 9. – user3552506 Apr 22 '14 at 23:20
  • 1
    If you are in the beginning stages of trying to write a parser, stop now and google Shunting-Yard Algorithm. – roippi Apr 22 '14 at 23:23
  • if the syntax is Python, you could [use `ast` module to parse it](http://stackoverflow.com/a/9558001/4279) e.g., `print(ast.dump(ast.parse('((a * 5) // ((10 - y) + z))', mode='eval')))` – jfs Apr 23 '14 at 00:39

2 Answers2

2

Using regular expressions (the re module):

>>> import re
>>> NAMES_AND_VALUES = re.compile(r'\w+')
>>> OPERATORS = re.compile(r'(?:\+|\*|\-|\/)+')

>>> string = '((a * 5) // ((10 - y) + z))'

>>> NAMES_AND_VALUES.findall(string)
['a', '5', '10', 'y', 'z']

>>> OPERATORS.findall(string)
['*', '//', '-', '+']

...and then of course you can just store these return values in lst1 and lst2 if you want. Or if lst1 and lst2 are pre-existing list objects, you can do lst1 += ... and lst2 += ....

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
0

Please try the following:

import re
str = '((a * 5) // ((10 - y) + z))'

>> filter(None, re.split (r'[()*+ /-]', str))
['a', '5', '10', 'y', 'z']

>> filter(None, re.split ('[()0-9a-z ]', str))
['*', '//', '-', '+']
Trufa
  • 39,971
  • 43
  • 126
  • 190
user1438233
  • 1,153
  • 1
  • 14
  • 30