[Python-talk] Does a string contain an integer

Kent Johnson kent37 at tds.net
Wed Apr 2 11:22:15 EDT 2008


Cole Tuininga wrote:
> Hey folks - quick Python question.  I'm looking for an elegant way to
> tell if a string is comprised of just an integer.  That is, if the
> string is simply an integer.  In perl, I would just use a regex like
> this:
> 
> if ($var =~ /^\d+$/) ...
> 
> I could use a regex to do this in Python, but is there a simpler and/or
> more elegant way to do it?

Maybe you like this:

try:
   int(var)
   # yep, it's an int
except ValueError:
   # nope, not an int

Kent


More information about the Python-talk mailing list