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

后端 未结 30 3847
暗喜
暗喜 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

    I also used the function you mentioned, but soon I notice that strings as "Nan", "Inf" and it's variation are considered as number. So I propose you improved version of your function, that will return false on those type of input and will not fail "1e3" variants:

    def is_float(text):
        try:
            float(text)
            # check for nan/infinity etc.
            if text.isalpha():
                return False
            return True
        except ValueError:
            return False
    

提交回复
热议问题