小编典典

测试Python字符串变量是否保留数字(int,float)或非数字str?

python

如果Python字符串变量中放置了整数,浮点数或非数字字符串,是否可以轻松测试该值的“类型”?

下面的代码是真实的(当然是正确的):

>>> strVar = "145"
>>> print type(strVar)
<type 'str'>
>>>

但是是否有Python函数或其他方法可以使我从上述的strVar设置查询中返回“ int”

也许像下面的废话代码和结果…

>>> print typeofvalue(strVar)
<type 'int'>

或更多废话:

>>> print type(unquote(strVar))
<type 'int'>

阅读 394

收藏
2021-01-20

共1个答案

小编典典

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

或者,如果您只想检查int,请更改第三行以try使用以下命令在内部阻塞:

int(var)
return int
2021-01-20