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

Paul Rubin http
Wed Dec 21 23:36:32 CET 2005


Erik Max Francis <max at alcyone.com> writes:
> The primary purpose of the .isdigit, etc. methods is to test whether a
> single character has a certain property.  There is, however, no
> special character data type in Python, and so by necessity those
> methods must be on strings, not characters.

Right, those two sentences contradict each other.  There's no
character data type so .isdigit can only test whether a string has a
certain property.  That certain property is whether string is a digit,
which is to say, a single-character string with one of a certain set
of values.

> Thus, you have basically two choices:  Have the methods throw
> exceptions for strings with a length different from one, or have them
> just iterate over every character in a string.  The latter is clearly
> a more useful functionality.

There is a third choice which is the natural and obvious one: have the
function do what its name indicates.  Return true if the arg is a
digit and false otherwise.  If iterating over the whole string is
useful (which it may be), then the function should have been named
differently, like .isdigits instead of .isdigit.

FWIW, I've usually tested for digit strings with re.match.  It never
occurred to me that isdigit tested a whole string.  



More information about the Python-list mailing list