How to test if object is an integer?
Mathias Lafeldt
mathias.lafeldt at googlemail.com
Mon Oct 17 16:02:03 EDT 2011
On Sat, Oct 15, 2011 at 1:44 AM, MrPink <tdsimpson at gmail.com> wrote:
>
> Is there a function in Python that can be used to test if the value in
> a string is an integer? I had to make one up for myself and it looks
> like this:
>
> def isInt(s):
> try:
> i = int(s)
> return True
> except ValueError:
> return False
According to [1], there're more Exceptions to test for:
try:
int(s)
return True
except (TypeError, ValueError, OverflowError): # int conversion failed
return False
[1] http://jaynes.colorado.edu/PythonIdioms.html, idiom "Catch errors
rather than avoiding them to avoid cluttering your code with special
cases"
-Mathias
More information about the Python-list
mailing list