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

Phil Harris phil.harris at zope.co.uk
Fri Nov 3 13:11:21 EST 2000


How about:

def isanum(str):
    try:
        a=int(str)
        return 1
    except:
        return 0


"Gaute B Strokkenes" <gs234 at cam.ac.uk> wrote in message
news:4a8zqyqxqv.fsf at kern.srcf.societies.cam.ac.uk...
|
| I've been using Python for something slightly more complicated than
| simple 'Hello World' programs for the first time in my life.  I find
| it very comfortable, but on the other hand I've also got this snippet
| in my program:
|
| 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.
|
| --
| Gaute Strokkenes                        http://www.srcf.ucam.org/~gs234/
| I have nostalgia for the late Sixties!  In 1969 I left my laundry with
|  a hippie!!  During an unauthorized Tupperware party it was chopped &
|  diced!





More information about the Python-list mailing list