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

后端 未结 30 3979
暗喜
暗喜 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:36

    So to put it all together, checking for Nan, infinity and complex numbers (it would seem they are specified with j, not i, i.e. 1+2j) it results in:

    def is_number(s):
        try:
            n=str(float(s))
            if n == "nan" or n=="inf" or n=="-inf" : return False
        except ValueError:
            try:
                complex(s) # for complex
            except ValueError:
                return False
        return True
    

提交回复
热议问题