Pythonic way to determine if a string is a number

Roy Smith roy at
Sun Feb 15 14:01:12 EST 2009

In article <mailman.9577.1234722607.3487.python-list at>,
 Christian Heimes <lists at> wrote:

> Philip Semanchuk schrieb:
> > 
> > On Feb 15, 2009, at 12:46 PM, python at wrote:
> > 
> >> What's the Pythonic way to determine if a string is a number? By
> >> number I mean a valid integer or float.
> > 
> > 
> > try:
> >    int(number)
> >    is_an_int = True
> > except:
> >    is_an_int = False
> Please don't teach new Python developers to use bare excepts. In fact
> never use bare excepts at all!

I agree that the bare except is incorrect in this situation, but I don't 
agree that you should *never* use them.

They make sense when you need to recover from any error that may occur, 
possibly as the last resort after catching and dealing with more specific 
exceptions. In an unattended embedded system (think Mars Rover), the 
top-level code might well be:

while 1:

or perhaps even (Range Safety Controller):


More information about the Python-list mailing list