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

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

    I needed to determine if a string cast into basic types (float,int,str,bool). After not finding anything on the internet I created this:

    def str_to_type (s):
        """ Get possible cast type for a string
    
        Parameters
        ----------
        s : string
    
        Returns
        -------
        float,int,str,bool : type
            Depending on what it can be cast to
    
        """    
        try:                
            f = float(s)        
            if "." not in s:
                return int
            return float
        except ValueError:
            value = s.upper()
            if value == "TRUE" or value == "FALSE":
                return bool
            return type(s)
    

    Example

    str_to_type("true") # bool
    str_to_type("6.0") # float
    str_to_type("6") # int
    str_to_type("6abc") # str
    str_to_type(u"6abc") # unicode       
    

    You can capture the type and use it

    s = "6.0"
    type_ = str_to_type(s) # float
    f = type_(s) 
    

提交回复
热议问题