Python – How to check if a string is a number (float)

castingfloating pointpythontype conversion

What is the best possible way to check if a string can be represented as a number in Python?

The function I currently have right now is:

def is_number(s):
        return True
    except ValueError:
        return False

Which, not only is ugly and slow, seems clunky. However I haven't found a better method because calling float in the main function is even worse.

Best Answer

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523"
>>> a.isdigit()
>>> b = "963spam"
>>> b.isdigit()

String Methods - isdigit(): Python2, Python3

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal