How can I tell when a string is in fact a number?

Alex Martelli aleaxit at yahoo.com
Mon Nov 6 10:49:45 EST 2000


"Dale Strickland-Clark" <dale at out-think.NOSPAMco.uk> wrote in message
news:eehd0t8ocpghnrm2c89dekanhmovteaaj2 at 4ax.com...
> Thomas Gagne <tgagne at ix.netcom.com> wrote:
>
> >Wouldn't it make better sense to return a boolean?  Is it possible to
modify
> >the String class to include a method, isNumber, that returns true or
false?
>
> 1 and 0 are Python's boolean values.

Python's "boolean" stuff follows the Silver Rule (not as
important as the Golden Rule, but still pretty precious):

"Be liberal in what you can accept, conservative in what you
generate, but never allow an error without a diagnostic".

"Conservative in what you generate": when Python must
'generate' Boolean values (comparisons and operator not),
it always generates 0 for false, 1 for true.  (Having a
special-purpose datatype just for that would be more
than 'conservative'... really "reactionary"!-).

"Liberal in what you can accept": just about _any_ Python
object can be used where Python 'accepts' a Boolean value
(if, while, and, or, not...): a few specific values are
designed as "false" (0-numbers, empty-sequences, ...),
all others are taken as "true".

"Never allow an error without a diagnostic": unknown
variables or functions, attempts to call a non-callable,
etc, are NOT taken as either 'true' or 'false' if
evaluated in any context where Python expects a Boolean
value -- rather, they raise appropriate exceptions and
this terminates the expectant context (up to the inner
try/except block that will handle that exception).  Of
course, this is just like for non-Boolean contexts:-).


Alex






More information about the Python-list mailing list