有没有办法了解字符串所包含的数据类型...这个问题没有什么逻辑,但请参阅下面的案例
varname = '444'
somefunc(varname) => int
varname = 'somestring'
somefunc(varname) => String
varname = '1.2323'
somefunc(varname) => float
Run Code Online (Sandbox Code Playgroud)
我的案例:我在列表中得到一个混合数据,但它们是字符串格式.
myList = ['1', '2', '1.2', 'string']
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种通用的方法来了解他们的数据是什么,以便我可以添加各自的比较.由于它们已经转换为字符串格式,我真的不能将列表(myList)称为混合数据......但仍然有办法吗?
per*_*eal 14
from ast import literal_eval
def str_to_type(s):
try:
k=literal_eval(s)
return type(k)
except:
return type(s)
l = ['444', '1.2', 'foo', '[1,2]', '[1']
for v in l:
print str_to_type(v)
Run Code Online (Sandbox Code Playgroud)
产量
<type 'int'>
<type 'float'>
<type 'str'>
<type 'list'>
<type 'str'>
Run Code Online (Sandbox Code Playgroud)
您可以使用ast.literal_eval()和type():
import ast
stringy_value = '333'
try:
the_type = type(ast.literal_eval(stringy_value))
except:
the_type = type('string')
Run Code Online (Sandbox Code Playgroud)