Sunday, July 1, 2018

In Python 2.x, is there anyway to check if a string can be converted to an integer?





I want a program to convert user input to an integer and store it in a list only if it can be. If the input is not able to be converted to an integer, the program should just continue and ignore the input.


Answer



The best approach here is to just try and convert it and ignore the error if the conversion fails. For example:



try:

your_list.append(int(user_input))
except ValueError:
pass

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...