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

Steven D'Aprano steve at REMOVETHIScyber.com.au
Wed Dec 21 06:27:49 EST 2005


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

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
try:
    n = int(s)
    print "Integer %d" % n
except ValueError:
    print "Not an integer %s" % s

try...except blocks are cheap in Python.


-- 
Steven.




More information about the Python-list mailing list