TypeError: ‘str’ does not support the buffer interface 建议两种可能的方法将字符串转换为字节:
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
哪种方法更 Pythonic?
原文由 Mark Ransom 发布,翻译遵循 CC BY-SA 4.0 许可协议
TypeError: ‘str’ does not support the buffer interface 建议两种可能的方法将字符串转换为字节:
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
哪种方法更 Pythonic?
原文由 Mark Ransom 发布,翻译遵循 CC BY-SA 4.0 许可协议
这比想象的要容易:
my_str = "hello world"
my_str_as_bytes = str.encode(my_str)
print(type(my_str_as_bytes)) # ensure it is byte representation
my_decoded_str = my_str_as_bytes.decode()
print(type(my_decoded_str)) # ensure it is string representation
您可以通过打印类型来验证。请参阅下面的输出。
<class 'bytes'>
<class 'str'>
原文由 hasanatkazmi 发布,翻译遵循 CC BY-SA 4.0 许可协议
4 回答4.4k 阅读✓ 已解决
4 回答3.8k 阅读✓ 已解决
1 回答3k 阅读✓ 已解决
3 回答2.1k 阅读✓ 已解决
1 回答4.5k 阅读✓ 已解决
1 回答3.8k 阅读✓ 已解决
1 回答2.8k 阅读✓ 已解决
如果您查看
bytes
的文档,它会将您指向bytearray
:所以
bytes
可以做的不仅仅是编码一个字符串。它是 Pythonic 的,它允许您使用任何类型的有意义的源参数调用构造函数。对于字符串编码,我认为
some_string.encode(encoding)
比使用构造函数更 Pythonic,因为它是最自我记录的——“获取此字符串并使用此编码对其进行编码”比bytes(some_string, encoding)
更清晰---
-- 使用构造函数时没有明确的动词。我检查了 Python 源代码。如果使用 CPython 将 unicode 字符串传递给
bytes
,它会调用 PyUnicode_AsEncodedString ,这是encode
的实现;因此,如果您自己调用encode
,您只是跳过了一个间接级别。另外,请参阅 Serdalis 的评论 –
unicode_string.encode(encoding)
也更像 Pythonic,因为它的逆是byte_string.decode(encoding)
并且对称性很好。