字节vs字节数组在Python 2.6和3中 [英] bytes vs bytearray in Python 2.6 and 3

查看:220
本文介绍了字节vs字节数组在Python 2.6和3中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python 2.6中的bytes vs bytearray进行实验.我不明白某些差异的原因.

I'm experimenting with bytes vs bytearray in Python 2.6. I don't understand the reason for some differences.

bytes迭代器返回字符串:

for i in bytes(b"hi"):
    print(type(i))

赠予:

<type 'str'>
<type 'str'>

但是bytearray迭代器返回int s:

for i in bytearray(b"hi"):
    print(type(i))

赠予:

<type 'int'>
<type 'int'>

为什么有区别?

我想编写可以很好地转换为Python 3的代码.那么,在Python 3中情况是否一样?

I'd like to write code that will translate well into Python 3. So, is the situation the same in Python 3?

推荐答案

在Python中,2.6字节只是str的别名.
引入这种伪类型"是为了(部分地)准备要与Python 3.0转换/兼容的程序(和程序员!),在Python 3.0中语义有严格区别,并用于str(系统上是unicode)和byte(是数组)八位字节,用于存储数据,但不存储文本)

In Python 2.6 bytes is merely an alias for str.
This "pseudo type" was introduced to [partially] prepare programs [and programmers!] to be converted/compatible with Python 3.0 where there is a strict distinction of semantics and use for str (which are systematically unicode) and bytes (which are arrays of octets, for storing data, but not text)

类似地,字符串文字的b前缀在2.6中无效,但是它在程序中是一个有用的标记,它明确标记程序员的意图是将字符串作为数据字符串而不是文本字符串.然后,当程序移植到Py3k时,2to3转换器或类似的实用程序可以使用此信息.

Similarly the b prefix for string literals is ineffective in 2.6, but it is a useful marker in the program, which flags explicitly the intent of the programmer to have the string as a data string rather than a text string. This info can then be used by the 2to3 converter or similar utilities when the program is ported to Py3k.

您可能要检查 SO问题以获取其他信息.

You may want to check this SO Question for additional info.

这篇关于字节vs字节数组在Python 2.6和3中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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