Testing if Python string variable holds number (int,float) or non-numeric str?

前端 未结 6 966
情书的邮戳
情书的邮戳 2020-12-19 11:23

If a Python string variable has had either an integer, floating point number or a non-numeric string placed in it, is there a way to easily test the \"type\" of that value?<

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 11:35

    I'd do it like this:

    def typeofvalue(text):
        try:
            int(text)
            return int
        except ValueError:
            pass
    
        try:
            float(text)
            return float
        except ValueError:
            pass
    
        return str
    

提交回复
热议问题