字节的行为从py2更改为py3 [英] Behavior change of bytes from py2 to py3

查看:90
本文介绍了字节的行为从py2更改为py3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题。看来 bytes()的行为在python3中已更改。在 py3的文档中,它现在被列为内置函数,除了结果是不可变的以外,其行为与 bytearray()相同。在py2文档中,它不会出现在同一位置。

I got curious after the discussion taking place on this question. It appears that the behavior of bytes() has changed in python3. In the docs for py3 it is now listed as a built-in function that behaves the same as bytearray() except for the result being immutable. It doesn't appear in the same place in py2 docs.

在挖掘文档一段时间后,我真的找不到任何详细说明从2变为3的内容。 ,但看起来确实有。有什么区别,为什么要更改?

In digging thru the docs for a while I couldn't really find anything detailing what's changed from 2 to 3, but it looks like something definitely has. What's the difference and why was it changed?

从评论中的链接问题中有人对py3进行了评论

From the linked question in the comments someone remarked with respect to py3

bytes(1)返回b'00'

bytes(1) returns b'00'

但在2.7.5

>>> bytes(1)
'1'


推荐答案

Python 3 bytes 构造函数采用可选的 int 参数,用于指定要输出的字节数。使用该构造函数将所有字节初始化为0( \x00 ),因此 bytes(1)== b'\x00'

The Python 3 bytes constructor takes an optional int parameter specifying the number of bytes to output. All bytes are initialized to 0 (\x00) with that constructor, so bytes(1) == b'\x00'.

Python 2 bytes 构造函数与 str相同,因此只是将其参数化为字符串:

The Python 2 bytes constructor is identical to str, and therefore just stringizes its argument:

Python 2.7.5 (v2.7.5:ab05e7dd2788, May 13 2013, 13:18:45) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> bytes is str
True

这篇关于字节的行为从py2更改为py3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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