Reputation: 69
input = (Columbia and (India or Singapore) and Malaysia)
output = [Columbia, India, Singapore, Malaysia]
Basically ignore the python keywords and brackets
I tried with the below code, but still not able to eliminate the braces.
import keyword
my_str=input()
l1=list(my_str.split(" "))
l2=[x for x in l1 if not keyword.iskeyword((x.lower()))]
print(l2)
Upvotes: 1
Views: 86
Reputation: 16496
try this one:
import re
from keyword import iskeyword
inp = '(Columbia and (India or Singapore) and Malaysia)'
c = re.compile(r'\b\w+\b')
print([i.group() for i in c.finditer(inp) if not iskeyword(i.group().lower())])
output :
['Columbia', 'India', 'Singapore', 'Malaysia']
without regex :
from keyword import iskeyword
inp = '(Columbia and (India or Singapore) and Malaysia)'
res = []
for i in inp.split():
stripped = i.strip('()[]{}')
if not iskeyword(stripped):
res.append(stripped)
print(res)
Upvotes: 2
Reputation: 2261
import keyword
my_str=input()
my_str = re.sub(r'[\(\)\[\]{}]','',my_str)
l1=list(my_str.split(" "))
l2=[x for x in l1 if not keyword.iskeyword((x.lower()))]
print(l2)
re.sub(r'[\(\)\[\]{}]','',my_str)
This will replace all kinds of braces with empty strings (thus removing them).
Upvotes: 2