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

Steven D'Aprano steve at
Wed Dec 21 12:27:49 CET 2005

On Wed, 21 Dec 2005 02:12:35 -0800, pinkfloydhomer at 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.

Okay, this has got to be homework, surely. This is the third, maybe the
fourth, question on this topic in a week or so :-)

In Python, the best solution to most "how can I check if X is a something"
questions is usually the Nike motto: Just Do It.

# s is some arbitrary string object
    n = int(s)
    print "Integer %d" % n
except ValueError:
    print "Not an integer %s" % s

try...except blocks are cheap in Python.


More information about the Python-list mailing list