在 Python 3 中,bytes
需要一种编码:
bytes(s, encoding="utf-8")
有没有办法设置默认编码,使 bytes
始终以 UTF-8 编码?
我想象的最简单的方法是
def bytes_utf8(s):
return bytes(s, encoding="utf-8")
最佳答案
documentation for bytes
将您重定向到 documentation for bytearray
,部分内容是:
The optional source parameter can be used to initialize the array in a few different ways:
- If it is a string, you must also give the encoding (and optionally, errors) parameters; bytearray() then converts the string to bytes using str.encode().
看起来没有办法提供默认值。
您可以使用 encode
方法,该方法确实有一个默认值,由 sys.getdefaultencoding()
给出。如果您需要更改默认值,请查看 this question但请注意,出于充分的理由删除了轻松执行此操作的功能。
import sys
print(sys.getdefaultencoding())
s.encode()
关于Python 3 设置默认字节编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31713117/