How to test if object is an integer?

Discussion in 'Python' started by MrPink, Oct 15, 2011.

  1. MrPink

    MrPink Guest

    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
     
    MrPink, Oct 15, 2011
    #1
    1. Advertising

  2. On Sat, Oct 15, 2011 at 10:44 AM, MrPink <> 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
     
    Chris Angelico, Oct 15, 2011
    #2
    1. Advertising

  3. On Sat, Oct 15, 2011 at 1:44 AM, MrPink <> 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
     
    Mathias Lafeldt, Oct 17, 2011
    #3
  4. MrPink

    Noah Hall Guest

    On Sat, Oct 15, 2011 at 12:44 AM, MrPink <> 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 the isdigit method, for example -

    >>> str = "1324325"
    >>> str.isdigit()

    True
    >>> str = "1232.34"
    >>> str.isdigit()

    False
    >>> str = "I am a string, not an int!"
    >>> str.isdigit()

    False
     
    Noah Hall, Oct 17, 2011
    #4
  5. MrPink

    Ian Kelly Guest

    On Mon, Oct 17, 2011 at 2:44 PM, Noah Hall <> wrote:
    > There's the isdigit method, for example -
    >
    >>>> str = "1324325"
    >>>> str.isdigit()

    > True
    >>>> str = "1232.34"
    >>>> str.isdigit()

    > False
    >>>> str = "I am a string, not an int!"
    >>>> str.isdigit()

    > False


    That works for non-negative base-10 integers. But:

    >>> "-1234".isdigit()

    False

    Cheers,
    Ian
     
    Ian Kelly, Oct 17, 2011
    #5
  6. MrPink

    Roy Smith Guest

    In article <>,
    Mathias Lafeldt <> wrote:

    > According to [1], there're more Exceptions to test for:
    >
    > try:
    > int(s)
    > return True
    > except (TypeError, ValueError, OverflowError): # int conversion failed
    > return False



    I don't think I would catch TypeError here. It kind of depends on how
    isInt() is defined. Is it:

    def isInt(s):
    "Return True if s is a string representing an integer"

    or is it:

    def isInt(s):
    "Return True if s (which must be a string) represents an integer"

    If the latter, then passing a non-string violates the contract, and the
    function should raise TypeError. If the former, then you could make
    some argument for catching the TypeError and returning False, but I
    think the second version is what most people have in mind for isInt().

    Can you even get an OverflowError any more in a modern Python?

    >>>

    int('99999999999999999999999999999999999999999999999999999999999999999')
    99999999999999999999999999999999999999999999999999999999999999999L
     
    Roy Smith, Oct 18, 2011
    #6
  7. MrPink

    Chris Kaynor Guest

    Python 2.6 running on Windows 7:
    >>> 99.0**99**99

    OverflowError: (34, 'Result too large')
    Traceback (most recent call last):
      File "<stdin-inspect>", line 1, in <module>
    OverflowError: (34, 'Result too large')

    However, from the documentation:
    "Because of the lack of standardization of floating point exception
    handling in C, most floating point operations also aren’t checked."
    (http://docs.python.org/library/exceptions.html#exceptions.OverflowError)

    Chris

    On Mon, Oct 17, 2011 at 5:33 PM, Roy Smith <> wrote:
    >
    > In article <>,
    >  Mathias Lafeldt <> wrote:
    >
    > > According to [1], there're more Exceptions to test for:
    > >
    > > try:
    > >     int(s)
    > >     return True
    > > except (TypeError, ValueError, OverflowError): # int conversion failed
    > >     return False

    >
    >
    > I don't think I would catch TypeError here.  It kind of depends on how
    > isInt() is defined.  Is it:
    >
    > def isInt(s):
    >  "Return True if s is a string representing an integer"
    >
    > or is it:
    >
    > def isInt(s):
    >  "Return True if s (which must be a string) represents an integer"
    >
    > If the latter, then passing a non-string violates the contract, and the
    > function should raise TypeError.  If the former, then you could make
    > some argument for catching the TypeError and returning False, but I
    > think the second version is what most people have in mind for isInt().
    >
    > Can you even get an OverflowError any more in a modern Python?
    >
    > >>>

    > int('99999999999999999999999999999999999999999999999999999999999999999')
    > 99999999999999999999999999999999999999999999999999999999999999999L
    > --
    > http://mail.python.org/mailman/listinfo/python-list
     
    Chris Kaynor, Oct 18, 2011
    #7
  8. MrPink

    Ian Kelly Guest

    On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor <> wrote:
    > Python 2.6 running on Windows 7:
    >>>> 99.0**99**99

    > OverflowError: (34, 'Result too large')
    > Traceback (most recent call last):
    >   File "<stdin-inspect>", line 1, in <module>
    > OverflowError: (34, 'Result too large')
    >
    > However, from the documentation:
    > "Because of the lack of standardization of floating point exception
    > handling in C, most floating point operations also aren’t checked."
    > (http://docs.python.org/library/exceptions.html#exceptions.OverflowError)


    I think what Roy meant was "can you even get an OverflowError from
    calling int() any more", to which I think the answer is no, since in
    modern Pythons int() will auto-promote to a long, and in Python 3
    they're even the same thing.
     
    Ian Kelly, Oct 18, 2011
    #8
  9. MrPink

    Yingjie Lan Guest

    ----- Original Message -----
    > From: Noah Hall <>
    > To: MrPink <>
    > Cc:
    > Sent: Tuesday, October 18, 2011 4:44 AM
    > Subject: Re: How to test if object is an integer?


    > There's the isdigit method, for example -
    >
    >>>> str = "1324325"
    >>>> str.isdigit()

    > True
    >>>> str = "1232.34"
    >>>> str.isdigit()

    > False
    >>>> str = "I am a string, not an int!"
    >>>> str.isdigit()

    > False
    >


    There are some corner cases to be considered with this approach:
    1. negative integers: '-3'
    2. strings starting with '0': '03'
    3. strings starting with one '+': '+3'
     
    Yingjie Lan, Oct 18, 2011
    #9
  10. On Mon, 17 Oct 2011 18:59:44 -0600, Ian Kelly wrote:

    > On Mon, Oct 17, 2011 at 6:40 PM, Chris Kaynor <>
    > wrote:
    >> Python 2.6 running on Windows 7:
    >>>>> 99.0**99**99

    >> OverflowError: (34, 'Result too large') Traceback (most recent call
    >> last):
    >>   File "<stdin-inspect>", line 1, in <module>
    >> OverflowError: (34, 'Result too large')
    >>
    >> However, from the documentation:
    >> "Because of the lack of standardization of floating point exception
    >> handling in C, most floating point operations also aren’t checked."
    >> (http://docs.python.org/library/

    exceptions.html#exceptions.OverflowError)
    >
    > I think what Roy meant was "can you even get an OverflowError from
    > calling int() any more", to which I think the answer is no, since in
    > modern Pythons int() will auto-promote to a long, and in Python 3
    > they're even the same thing.



    You can still get an OverflowError:

    >>> inf = float('inf')
    >>> int(inf)

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    OverflowError: cannot convert float infinity to integer


    and similarly for Decimal('inf') as well.


    --
    Steven
     
    Steven D'Aprano, Oct 18, 2011
    #10
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. =?Utf-8?B?Sm9l?=

    CType(x,Integer) vs. Integer.Parse(x)

    =?Utf-8?B?Sm9l?=, Feb 6, 2006, in forum: ASP .Net
    Replies:
    7
    Views:
    5,976
    =?Utf-8?B?RGF2aWQgQW50b24=?=
    Feb 7, 2006
  2. =?ISO-8859-1?Q?Thomas_Gagn=E9?=

    No Math.min(Integer, Integer)?

    =?ISO-8859-1?Q?Thomas_Gagn=E9?=, Jul 29, 2003, in forum: Java
    Replies:
    0
    Views:
    538
    =?ISO-8859-1?Q?Thomas_Gagn=E9?=
    Jul 29, 2003
  3. Sebastian Stelzer

    How do I add an Integer to another Integer?

    Sebastian Stelzer, Oct 14, 2004, in forum: Java
    Replies:
    2
    Views:
    521
    Yu SONG
    Oct 15, 2004
  4. Sebastian Stelzer

    How do I add an Integer to another Integer?

    Sebastian Stelzer, Oct 14, 2004, in forum: Java
    Replies:
    6
    Views:
    45,836
    JavaBean2010
    Apr 7, 2010
  5. Skybuck Flying

    Call oddities: &Test() vs &Test vs Test

    Skybuck Flying, Oct 4, 2009, in forum: C Programming
    Replies:
    1
    Views:
    748
    Skybuck Flying
    Oct 4, 2009
Loading...

Share This Page