Assume I'd like to convert a list of strings to integer, but it cannot be done for all elements.
I know this works:
a = ['2.0','3.0','4.0','5.0','Cherry']
b = []
for k in a:
try:
int(k)
b.append(int(k))
except:
pass
print b
> [2, 3, 4, 5]
But is there also a shorter way of doing this? I thought about something like:
b = [try int(k) for k in a]
This may sound like a silly question since I do have a working solution, but I have often been shown shorter ways of doing the same thing and always appreciated this kind of help. I am using Python 2.7
Thanks!
Edit: sorry, I was also talking about floating point. I just changed my example data