How do I check if a string is a number (float)?

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):
    try:
        float(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.


Which, not only is ugly and slow

I'd dispute both.

A regex or other string parsing would be uglier and slower.

I'm not sure that anything much could be faster than the above. It calls the function and returns. Try/Catch doesn't introduce much overhead because the most common exception is caught without an extensive search of stack frames.

The issue is that any numeric conversion function has two kinds of results

  • A number, if the number is valid
  • A status code (eg, via errno) or exception to show that no valid number could be parsed.
  • C (as an example) hacks around this a number of ways. Python lays it out clearly and explicitly.

    I think your code for doing this is perfect.


    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()
    True
    >>> b = "963spam"
    >>> b.isdigit()
    False
    

    String Methods - isdigit()

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


    There is one exception that you may want to take into account: the string 'NaN'

    If you want is_number to return FALSE for 'NaN' this code will not work as Python converts it to its representation of a number that is not a number (talk about identity issues):

    >>> float('NaN')
    nan
    

    Otherwise, I should actually thank you for the piece of code I now use extensively. :)

    G.

    链接地址: http://www.djcxy.com/p/3556.html

    上一篇: 如何在Java中分割字符串

    下一篇: 如何检查字符串是否是数字(浮点数)?