Python中的类型 [英] Typecasting in Python

查看:201
本文介绍了Python中的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将Python中的字符串转换为其他类型,例如无符号和有符号的8,16,32和64位int,双精度浮点数和字符串。

I need to convert strings in Python to other types such as unsigned and signed 8, 16, 32, and 64 bit ints, doubles, floats, and strings.

推荐答案

您可以将字符串转换为32位有符号整数与 int function:

You can convert a string to a 32-bit signed integer with the int function:

str = "1234"
i = int(str)  // i is a 32-bit integer

如果字符串不表示整数,获取 ValueError 异常。但请注意,如果字符串表示一个整数,但该整数不适合32位有符号int,那么你实际上会得到一个类型 long

If the string does not represent an integer, you'll get a ValueError exception. Note, however, that if the string does represent an integer, but that integer does not fit into a 32-bit signed int, then you'll actually get an object of type long instead.

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

You can then convert it to other widths and signednesses with some simple math:

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

您可以将字符串转换为浮点, code> float 函数:

You can convert strings to floating point with the float function:

f = float("3.14159")

Python浮动是其他语言引用的 double 即它们是64位。 Python中没有32位浮动广告。

Python floats are what other languages refer to as double, i.e. they are 64-bits. There are no 32-bit floats in Python.

这篇关于Python中的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆