在Python 3中,当我索引一个字节数组时会发生什么? [英] In Python 3, what is happening when I index a bytearray?

查看:189
本文介绍了在Python 3中,当我索引一个字节数组时会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3中,我可以通过编码字符串来创建字节数组:

In Python 3, I can create a bytearray by encoding a string:

>>> foo = 'abc'
>>> bar = foo.encode('utf-8')
>>> bar
b'abc'

但是当我索引该字节数组时,我得到了其他东西:

But when I index that byte array, I get something else:

>>> bar[0]
97

这是什么,为什么不是

b'a'

推荐答案

这是一个小整数,因为这就是在.

It's a small int, because that's how indexing bytes is defined in PEP 3137: "Immutable Bytes and Mutable Buffer".

索引

索引字节和字节数组返回小整数[...]

Indexing

Indexing bytes and bytearray returns small ints [...]

对字节数组对象项的赋值接受range(256)中的int. [...]

Assignment to an item of a bytearray object accepts an int in range(256). [...]

如果要b'a',请改为切片.

3>> b'abc'[0:1]
b'a'

这篇关于在Python 3中,当我索引一个字节数组时会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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