简体   繁体   中英

How do I check if a string is a float number or an integer number?

"1.0".isnumeric() -> False

I need to know if that string is actually a float number or an integer number because there although the string is in fact a float number the. isnumeric() returns False

What you can do is convert the string into its actual datatype using ast.literal_eval method and then use the isinstance method to check if it is a float number or not.

>>> import ast
>>> string = '1.0'
>>>
>>> num = ast.literal_eval(string)
>>> num
1.0
>>> isinstance(num,float)
True
>>>

Same way you can check if it is an integer. Hope this answers your question.

Try this function:

def is_numeric(some_string):
    try:
        float(some_string)
        return True
    except ValueError:
        return False


if __name__ == "__main__":
    print(is_numeric("123"))
    print(is_numeric("1.0"))
    print(is_numeric("1.0asd"))

Output:

True
True
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM