How to test if object is an integer?

Chris Angelico rosuav at gmail.com
Fri Oct 14 20:55:46 EDT 2011


On Sat, Oct 15, 2011 at 10: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

There's some ambiguity in the definition of "is an integer". For
instance, is "0x100" an integer? Is "0800"? If your definition of "is
an integer" is "can be passed to int() without triggering an
exception" (which is probably the most useful), then your above code
is about perfect. The only change I'd make is to not have an isInt
function at all, but simply to try/except at the point where you need
to make the conversion.

ChrisA



More information about the Python-list mailing list