I have a list something like this:

l=["1", "a", "b", "2", "c"]

I want to extract the list ["1", "2"] or [1, 2] from l.

In other words, I want to extract elements e which int(e) is valid.

1 Answers

2
Adam Smith On

two basic ways to do this.

  1. str.isdigit is a string method that will return a bool whether or not that number is digit-only. Note that assert '1.5'.isdigit() == False.

  2. int('1') works, but int('a') throws a ValueError. You can catch that error, and only accept values that don't throw errors.