如何附加到python 3中的字节

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27001419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:16:58  来源:igfitidea点击:

How to append to bytes in python 3

pythonpython-3.x

提问by felixbade

I have some bytes.

我有一些bytes

b'\x01\x02\x03'

And an intin range 0..255.

并且int在范围0..255。

5

Now I want to append the intto the byteslike this:

现在我想将 附加intbytes这样的:

b'\x01\x02\x03\x05'

How to do it? There is no appendmethod in bytes. I don't even know how to make the integer become a single byte.

怎么做?中没有append方法bytes。我什至不知道如何使整数成为单个字节。

>>> bytes(5)
b'\x00\x00\x00\x00\x00'

采纳答案by simonzack

bytesis immutable. Use bytearray.

bytes是不可变的。使用bytearray.

xs = bytearray(b'\x01\x02\x03')
xs.append(5)

回答by Ashwini Chaudhary

First of all passing an integer(say n) to bytes()simply returns an bytes string of nlength with null bytes. So, that's not what you want here:

首先传递一个整数(比如n)来bytes()简单地返回一个n长度为空字节的字节字符串。所以,这不是你想要的:

Either you can do:

你可以这样做:

>>> bytes([5]) #This will work only for range 0-256.
b'\x05'

Or:

或者:

>>> bytes(chr(5), 'ascii')
b'\x05'

As @simonzack already mentioned that bytes are immutable, so to update(or better say re-assign it to a new string) its value you need to use the +=operator.

正如@simonzack 已经提到字节是不可变的,因此要更新(或者更好地将其重新分配给新字符串)它的值,您需要使用+=运算符。

>>> s = b'\x01\x02\x03'
>>> s += bytes([5])     #or s = s + bytes([5])
>>> s
b'\x01\x02\x03\x05'

>>> s = b'\x01\x02\x03'
>>> s += bytes(chr(5), 'ascii')   ##or s = s + bytes(chr(5), 'ascii')
>>> s
b'\x01\x02\x03\x05'

Help on bytes():

帮助bytes()

>>> print(bytes.__doc__)
bytes(iterable_of_ints) -> bytes
bytes(string, encoding[, errors]) -> bytes
bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
bytes() -> empty bytes object

Construct an immutable array of bytes from:
  - an iterable yielding integers in range(256)
  - a text string encoded using the specified encoding
  - any object implementing the buffer API.
  - an integer

Or go for the mutable bytearrayif you need a mutable object and you're only concerned with the integers in range 0-256.

或者,bytearray如果您需要一个可变对象并且您只关心 0-256 范围内的整数,则选择可变对象。