Python 3 设置默认字节编码
Python 3 set default bytes encoding
在Python3中,bytes
需要编码:
bytes(s, encoding="utf-8")
有没有办法设置默认编码,这样 bytes
总是以 UTF-8 编码?
我想象的最简单的方法是
def bytes_utf8(s):
return bytes(s, encoding="utf-8")
documentation for bytes
redirects you to the 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()
在Python3中,bytes
需要编码:
bytes(s, encoding="utf-8")
有没有办法设置默认编码,这样 bytes
总是以 UTF-8 编码?
我想象的最简单的方法是
def bytes_utf8(s):
return bytes(s, encoding="utf-8")
documentation for bytes
redirects you to the 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()