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

Quinn Dunkan quinn at spew.ugcs.caltech.edu
Tue Nov 7 12:40:41 EST 2000


On 05 Nov 2000 14:50:16 +0000, Gaute B Strokkenes <gs234 at cam.ac.uk> wrote:
>def isanum(str):
>    # FIXME: Surely there must be a sane way of doing this.
>    from string import find, digits
>    for i in range(len(str)):
>        if find(digits, str[i]) == -1:
>            return 0
>    return 1
>
>As the comment says, I'm sure there must be a more straightforward way
>to do this.  However, I can't find out how, though I'm sure that it is
>really my relative unfamiliarity with Python that is to blame.

Well, people seem to be having a lot of fun with this one, but I'm sort of
surprised that no one has pointed out my solution-of-choice yet:

s.isdigit() # python 2

It obviously doesn't do floats or anything, but that doesn't seem to be in the
specification.



More information about the Python-list mailing list