python 2.7 和 PEP-358 中的字节类型 [英] the bytes type in python 2.7 and PEP-358

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

问题描述

根据PEP 358,字节对象用于存储可变字节序列(0-255),如果不是这种情况,则提高.

但是,我的 python 2.7 另有说明

<预><代码>>>>字节([1,2,3])'[1, 2, 3]'>>>字节([280])'[280]'>>>字节是 str真的>>>字节<输入'str'>

有没有人知道 PEP 被宣布为 Final,但实现不符合的原因?

解决方案

bytes 类型是在 Python 3 中引入的,但 PEP 中讨论的是可变序列(bytes 是不可变的),它是在 Python 2.6 中以 bytearray 的名称引入的.

PEP 显然没有按照规定实施(并且确实说它部分被 PEP 3137),但我认为这只是重命名的问题,而不是缺少功能的问题.在 Python 2 中,bytes 只是 str 的别名,以帮助向前兼容,因此这里是一个红鲱鱼.

字节数组用法示例:

<预><代码>>>>a = bytearray([1,2,3])>>>[0] = 5>>>一种字节数组(b'\x05\x02\x03')

According to PEP 358, a bytes object is used to store a mutable sequence of bytes (0-255), raising if this is not the case.

However, my python 2.7 says otherwise

>>> bytes([1,2,3])
'[1, 2, 3]'
>>> bytes([280])
'[280]'
>>> bytes is str
True
>>> bytes
<type 'str'>

Does anyone have a clue on the reason why the PEP is declared Final, but the implementation does not conform ?

解决方案

The bytes type was introduced in Python 3, but what's being discussed in the PEP is a mutable sequence (bytes is immutable) which was introduced in Python 2.6 under the name bytearray.

The PEP clearly wasn't implemented as stated (and it does say that it was partially superseded by PEP 3137) but I think it's only a question of things being renamed, not features missing. In Python 2 bytes is just an alias for str to aid forward compatibility and so is a red-herring here.

Example bytearray usage:

>>> a = bytearray([1,2,3])
>>> a[0] = 5
>>> a
bytearray(b'\x05\x02\x03')

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

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