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

Roy Smith roy at panix.com
Wed Dec 21 08:21:08 EST 2005


In article <1135159955.302316.24060 at g43g2000cwa.googlegroups.com>,
 "pinkfloydhomer at gmail.com" <pinkfloydhomer at gmail.com> wrote:

> How do I check if a string contains (can be converted to) an int? I
> want to do one thing if I am parsing and integer, and another if not.
> 
> /David

The most straight-forward thing is to try converting it to an int and see 
what happens.

try:
   int(s)
except ValueError:
   print "sorry, '%s' isn't a valid integer" % s



More information about the Python-list mailing list