我想知道是否有一种优雅而简单的方法可以将字符串(我知道可以转换为数字)转换为相应的数字类型。例如,如果我的字符串表示一个整数,我希望将该值转换为 int; long、float 等也是如此。
请您参考如下方法:
您可以使用 ast.literal_eval。
import ast
examples = ["1", "1.5", "999999999999999999999999999999999999999999", "23+42j"]
for item in examples:
result = ast.literal_eval(item)
print result
print type(result)
结果:
1
<type 'int'>
1.5
<type 'float'>
999999999999999999999999999999999999999999
<type 'long'>
(23+42j)
<type 'complex'>
