[英]How to convert string to byte in Python, and add the values in the byte?
我正在使用 Python 2.7。
我得到了这个函数的文档字符串:
def test(a, b):
''' takes two bytes, returns the the bytes when the two bytes are added up
(bytes, bytes) -> bytes
j = 0
k = j + b[0]
我尝试这样做(有人告诉我这将是该函数的有效输入并遵循文档字符串):
test(b"2402", b"testing"):
但这引发了一个错误说
TypeError: unsupported operand type(s) for +: 'int' and 'str'
根据我的理解,字节由 1 和 0(即整数)组成。 那么我不应该能够添加字节的每个索引吗?
示例: test(b"123", b"testing")
a 和 b 将是字节(由 1 和 0 组成)。 我应该能够将数字相加,让它等于 x,然后返回 b"x"。
编辑:函数本身不需要解决,我只是用一个例子来说明我想要的。 我只想知道如何在 Python 2.7 中将字符串转换为字节。
当您使用 python 2 时,请使用
bytearray("2402")
或者
"2402".encode('utf-8')
如果你决定切换到 python 3.x,试试这个:
test(bytes("2402", 'utf-8'), bytes("testing", 'utf-8'))
要将字符串转换为字节或将字节转换为字符串,您还应该提供编码,如果您有字节,则无法使用 str 获得正确的结果,但您应该使用如下编码:
b"abcde".decode("utf-8")
您应该考虑另一件事,即对字节进行索引不会返回一个字节,而是返回整数,试试这个:
>>>type(b[0])
<class 'int'>
因为 bytes 和 bytearray 对象是整数序列(0 到 255 之间)
该函数在 python3 中有效,因为在 py3 中,对于字节对象b
, b[0]
将是一个整数:
>>> type(b'abc'[0])
<class 'int'>
但是当您使用 python2 时, b[0]
将是一个 str:
>>> type(b'abc'[0])
<type 'str'>
不允许将 str 和 int 添加在一起。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.