How to test if object is an integer?

惜悯 wauue at qq.com
Fri Oct 14 21:00:11 EDT 2011


retrun True if type(i) is int else False
 
 
------------------ Original ------------------
From:  "Chris Angelico"<rosuav at gmail.com>;
Date:  Sat, Oct 15, 2011 08:55 AM
To:  "python-list"<python-list at python.org>; 

Subject:  Re: How to test if object is an integer?

 
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
-- 
http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111015/eeed1bc9/attachment-0001.html>


More information about the Python-list mailing list