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

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

    Updated after Alfe pointed out you don't need to check for float separately as complex handles both:

    def is_number(s):
        try:
            complex(s) # for int, long, float and complex
        except ValueError:
            return False
    
        return True
    

    Previously said: Is some rare cases you might also need to check for complex numbers (e.g. 1+2i), which can not be represented by a float:

    def is_number(s):
        try:
            float(s) # for int, long and float
        except ValueError:
            try:
                complex(s) # for complex
            except ValueError:
                return False
    
        return True
    

提交回复
热议问题