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

Alex Martelli aleax at mail.comcast.net
Wed Dec 21 11:32:07 EST 2005


Erik Max Francis <max at alcyone.com> wrote:

> 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.
> 
>       try:
>           x = int(aPossibleInt)
>           ... do something with x ...
>       except ValueError:
>           ... do something else ...

Correct, but even better is a slight variation:

        try:
            x = int(aPossibleInt)
        except ValueError:
            ... do something else ...
        else:
            ... do something with x ...

this way, you avoid accidentally masking an unexpected ValueError in the
"do something with x" code.

Keeping your try-clauses as small as possible (as well as your
except-conditions as specific as possible) is important, to avoid
masking bugs and thus making their discovery hader.


Alex



More information about the Python-list mailing list