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

前端 未结 6 941
情书的邮戳
情书的邮戳 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:51

    import ast
    def type_of_value(var):
        try:
           return type(ast.literal_eval(var))
        except Exception:
           return str
    

    Or, if you only want to check for int, change the third line to block inside try with:

    int(var)
    return int
    

提交回复
热议问题