How to check if a string "is" an int?

bonono at gmail.com bonono at gmail.com
Wed Dec 21 08:15:23 EST 2005


Steven D'Aprano wrote:
> If you really wanted to waste CPU cycles, you could do this:
>
> s = "1579"
> for c in s:
>     if not c.isdigit():
>         print "Not an integer string"
>         break
> else:
>     # if we get here, we didn't break
>     print "Integer %d" % int(s)
>
>
> but notice that this is wasteful: first you walk the string, checking each
> character, and then the int() function has to walk the string again,
> checking each character for the second time.
>
Wasteful enough that there is a specific built-in function to do just
this ?




More information about the Python-list mailing list