简体   繁体   English

自动将字符串转换为正确的数字类型

[英]Automatically convert string to the right numerical type

I was wondering if there's an elegant and easy way to convert a string (that I know can be converted to a number) to the corresponding numerical type. 我想知道是否存在一种优雅,简便的方法来将字符串(我知道可以转换为数字)转换为相应的数字类型。 For example, if my string represents an integer, I want the value converted to int ; 例如,如果我的字符串表示一个整数,我希望将值转换为int same for long , float , and so on. 同样适用于longfloat等。

You could use ast.literal_eval . 您可以使用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)

Result: 结果:

1
<type 'int'>
1.5
<type 'float'>
999999999999999999999999999999999999999999
<type 'long'>
(23+42j)
<type 'complex'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM