Check if string is a real number

Is there a quick way to find if a string is a real number, not counting it as a character at a time and doing isdigit()for each character? I want to be able to check floating point numbers, for example 0.03001.

+3
source share
4 answers

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

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

Note that this internally still loops your line, but this is inevitable.

+12
source
>>> 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 it:

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

If you want a floating point number, replace intwith float(thanks to @cobbal).

+7
source

:

import re

def is_float(str):
    if re.match(r"\d+\.*\d*", str):
        return True
    else:
        return False
+1

:

def verify_real_number(item):
""" Method to find if an 'item'is real number"""

item = str(item).strip()
if not(item):
    return False
elif(item.isdigit()):
    return True
elif re.match(r"\d+\.*\d*", item) or re.match(r"-\d+\.*\d*", item):
    return True
else:
    return False
0

All Articles