Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if string is a real number

Is there a quick way to find if a string is a real number, short of reading it a character at a time and doing isdigit() on each character? I want to be able to test floating point numbers, for example 0.03001.

like image 206
Illusionist Avatar asked Nov 28 '22 18:11

Illusionist


2 Answers

>>> a = "12345" # good number
>>> int(a)
12345
>>> b = "12345G" # bad number
>>> int(b)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '12345G'

You can do that:

def isNumber(s):
    try:
        int(s)
    except ValueError:
        return False
    return True

If you want a float number, replace int by float (thanks to @cobbal).

like image 40
bfontaine Avatar answered Dec 01 '22 07:12

bfontaine


If you mean an float as a real number this should work:

def isfloat(str):
    try: 
        float(str)
    except ValueError: 
        return False
    return True

Note that this will internally still loop your string, but this is inevitable.

like image 180
orlp Avatar answered Dec 01 '22 08:12

orlp