Python从字符串返回适当的类型

ali*_*oli -1 python types

假设需要将字符串转换为适当的类型.例如,如果字符串为:"1.0"则返回1.0 <type 'float'>
"[1.0,2.1,3]"返回[1.0, 2.1, 3] <type 'list'>

这样做有一种聪明的方法吗?

Eri*_*ric 7

import ast
val = ast.literal_eval(input_str)
print type(val)
Run Code Online (Sandbox Code Playgroud)