This is the way to go:
x = ['2', '3/4', '+', '4', '3/5']
g = []
for i in x:
try:
g.append(int(i))
except ValueError:
pass
print(g) # [2, 4]
What you tried is not a try-except
block. It is an if
statement which failed because '4'
is not an int
instance (4
is, notice the quotes); it is a string.
There are of course other ways to do it too as mentioned in the comments. I only went for the try-except
because you mentioned it in your comments.
solved Python List parsing (incude int, str)