在Python中进行类型转换

use*_*646 21 python string int casting bit

我需要将Python中的字符串转换为其他类型,例如unsigned和signed 8,16,32和64位int,double,float和strings.

我怎样才能做到这一点?

Ada*_*eld 40

您可以使用以下int函数将字符串转换为32位有符号整数:

str = "1234"
i = int(str)  // i is a 32-bit integer
Run Code Online (Sandbox Code Playgroud)

如果字符串不表示整数,则会出现ValueError异常.但请注意,如果字符串确实表示一个整数,但该整数不适合32位signed int,那么实际上您将获得一个类型的对象long.

然后,您可以使用一些简单的数学将其转换为其他宽度和签名:

s8 = (i + 2**7) % 2**8 - 2**7      // convert to signed 8-bit
u8 = i % 2**8                      // convert to unsigned 8-bit
s16 = (i + 2**15) % 2**16 - 2**15  // convert to signed 16-bit
u16 = i % 2**16                    // convert to unsigned 16-bit
s32 = (i + 2**31) % 2**32 - 2**31  // convert to signed 32-bit
u32 = i % 2**32                    // convert to unsigned 32-bit
s64 = (i + 2**63) % 2**64 - 2**63  // convert to signed 64-bit
u64 = i % 2**64                    // convert to unsigned 64-bit
Run Code Online (Sandbox Code Playgroud)

您可以使用以下float函数将字符串转换为浮点数:

f = float("3.14159")
Run Code Online (Sandbox Code Playgroud)

Python浮动是其他语言所指的double,即它们是64位.Python中没有32位浮点数.

  • 有趣的是,不同的可以接受完全相同的问题的答案http://stackoverflow.com/questions/374318/conversion-of-unicode-string-in-python#374335 (3认同)