Python中字节到字符串的转换似乎没有按预期工作

2024-04-23 14:13:46 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么在python3中

print(str(b"Hello"))

输出b'Hello'而不是像常规文本字符串那样只输出Hello?从最相关的二进制字符串类型创建一个str对象看起来很简单,但最终是显式的。你知道吗


Tags: 对象字符串文本类型hello二进制常规python3
3条回答

你为什么想让这个“起作用”?bytes对象是bytes对象,它在python3中的字符串表示形式就是这种形式。你可以把它的内容转换成一个合适的文本字符串(在Python3中-在Python2中是“unicode”对象),你必须把它解码成文本。你知道吗

为此你需要知道编码-

请尝试以下操作:

print(b"Hello".decode("latin-1"))

请注意,假定的“拉丁-1”文本编解码器将透明地将非ASCII范围(128-256)的代码转换为unicode。它是Windows默认用于西欧语言的编解码器。你知道吗

“utf-8”编解码器可以表示更大范围的字符,并且是国际文本的首选编码-但是如果您的字节字符串没有正确地由utf-8字符组成,您可能会在进程中遇到UnicodeDecode错误。你知道吗

请阅读http://www.joelonsoftware.com/articles/Unicode.html以正确理解课文内容。你知道吗

在python3中,bytes.__str__未定义,因此在对象上使用str()时,使用bytes.__repr__。注意,print()对传入的对象调用str(),因此这里的调用是完全冗余的。你知道吗

如果需要文本,请显式解码:

print(b'Hello'.decode('ascii'))

^{} type可以显式地处理bytes对象,但前提是(再次)提供显式编解码器来解码字节:

print(str(b'Hello', 'ascii'))

文档对这种行为非常明确:

If neither encoding nor errors is given, str(object) returns object.__str__(), which is the “informal” or nicely printable string representation of object. For string objects, this is the string itself. If object does not have a __str__() method, then str() falls back to returning repr(object).

If at least one of encoding or errors is given, object should be a bytes-like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors).

以及

Passing a bytes object to str()without the encoding or errors arguments falls under the first case of returning the informal string representation.

强调我的。你知道吗

事先,对不起我的英语。。。你知道吗

嘿,我几个星期前就有这个问题了。正如上面所说的。 如果解码过程中的异常无关紧要,这里有一个提示。在这种情况下,您可以使用:

bytesText.decode(textEncoding, 'ignore')

例如:

>>> b'text \xab text'.decode('utf-8', 'ignore')  # Using UTF-8 is nice as you might know!
'text  text'                                     # As you can see, the « (\xab) symbol was
                                                 # ignored :D

相关问题 更多 >