How can I determine if the string is a number (integer plus real numbers) in Python?

Asked 2 years ago, Updated 2 years ago, 96 views

If you use isdigit(), only the integer is true, and the real type shows False I don't think there's anything like isfloat() what should I do?

python casting floating-point type-conversion

2022-09-22 22:35

1 Answers

Try to make an exception handling.

You can simply write it like this

# coding=utf-8
def is_number(num):
    try:
        float(num)
        If returnTrue #num can be converted to float
    exceptionValueError: #num cannot be converted to float
        return False

is_number("3.24242424")
is_number("5")

However, the above method is is_number("NaN") returns True so if you want to treat all of these exceptions as False Use as follows

# coding=utf-8
def is_number(num):
    try:
        judge = str(float(num))
        return False if(judge=='nan' or judge=='inf' or judge =='-inf') else True
    exception(ValueError, type): #num cannot be converted to float
        return False


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.