Check if string is a real number

喜欢而已 提交于 2019-12-10 21:59:32

问题


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.


回答1:


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.




回答2:


>>> 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).




回答3:


There is also another way using regular expression:

import re

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



回答4:


Method to verify real number:

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


来源:https://stackoverflow.com/questions/5956240/check-if-string-is-a-real-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!