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

后端 未结 30 3841
暗喜
暗喜 2020-11-21 05:16

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_numb         


        
30条回答
  •  借酒劲吻你
    2020-11-21 05:41

    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.

提交回复
热议问题