Python 将字节字符串转换为字节或字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35310695/
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 16:16:17  来源:igfitidea点击:

Convert byte string to bytes or bytearray

pythonbytebytearray

提问by IAbstract

I have a string as follows:

我有一个字符串如下:

  b'\x00\x00\x00\x00\x07\x80\x00\x03'

How can I convert this to an array of bytes? ... and back to a string from the bytes?

如何将其转换为字节数组?...并从字节返回一个字符串?

采纳答案by steel.ne

in python 3:

在python 3中:

>>> a=b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>> b = list(a)
>>> b
[0, 0, 0, 0, 7, 128, 0, 3]
>>> c = bytes(b)
>>> c
b'\x00\x00\x00\x00\x07\x80\x00\x03'
>>>

回答by RafaelCaballero

From string to array of bytes:

从字符串到字节数组:

a = bytearray.fromhex('00 00 00 00 07 80 00 03')

or

或者

a = bytearray(b'\x00\x00\x00\x00\x07\x80\x00\x03')

and back to string:

并回到字符串:

key = ''.join(chr(x) for x in a)