Reputation: 45
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?
Upvotes: 0
Views: 135
Reputation: 1233
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))
['*', '//', '-', '+']
Upvotes: 0
Reputation: 38217
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 += ...
.
Upvotes: 2