似乎有两种不同的方法将字符串转换为字节,如TypeError: 'str' does not support the buffer interface的答案所示
哪种方法更好或更好Pythonic?或者只是个人偏好的问题?
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
似乎有两种不同的方法将字符串转换为字节,如TypeError: 'str' does not support the buffer interface的答案所示
哪种方法更好或更好Pythonic?或者只是个人偏好的问题?
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
5 回答
它比想象的容易:
如果您查看
bytes
的文档,它会指向bytearray:所以
bytes
可以做的不仅仅是编码一个字符串 . 它是Pythonic,它允许你用任何类型的有意义的源参数调用构造函数 .对于编码字符串,我认为
some_string.encode(encoding)
比使用构造函数更Pythonic,因为它是最自我的文档 - "take this string and encode it with this encoding"比bytes(some_string, encoding)
更清晰 - 当你使用构造函数时没有明确的动词 .Edit: 我检查了Python源代码 . 如果使用CPython将unicode字符串传递给
bytes
,则会调用PyUnicode_AsEncodedString,这是encode
的实现;所以如果你自己打电话给_635223,你就是在跳过一个间接层 .另外,请参阅Serdalis的评论 -
unicode_string.encode(encoding)
也更像Pythonic,因为它的反面是byte_string.decode(encoding)
并且对称性很好 .绝对最好的方式既不是2,也不是3 . 自Python 3.0以来,encode的第一个参数默认为
'utf-8'
. 因此最好的方法是这也会更快,因为默认参数不会导致C代码中的字符串
"utf-8"
,而是NULL
,这要检查得快得多!这里有一些时间:
尽管有警告,但在重复运行后时间非常稳定 - 偏差仅为~2% .
使用不带参数的
encode()
不兼容Python 2,因为在Python 2中默认的字符编码是ASCII .您可以使用以下命令将字符串转换为字节
a_string.encode()
您可以使用以下命令将字节转换为字符串:
some_bytes.decode()
bytes.decode
和str.encode
具有encoding='utf-8'
作为默认值 .以下函数(取自Effective Python)可能有助于将
str
转换为bytes
并将bytes
转换为str
: