gpt4 book ai didi

python - 为什么 Python3 str(bytes) 转换为文字字符串 b''

转载 作者:行者123 更新时间:2023-12-02 19:20:28 27 4
gpt4 key购买 nike

我使用的是python3。以下是解释问题的示例。

# python3
Python 3.6.8 (default, Sep 26 2019, 11:57:09)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.getdefaultencoding()
'utf-8'
>>> help(str)
| str(object='') -> str
| str(bytes_or_buffer[, encoding[, errors]]) -> str
|
| Create a new string object from the given object. If encoding or
| errors is specified, then the object must expose a data buffer
| that will be decoded using the given encoding and error handler.
| Otherwise, returns the result of object.__str__() (if defined)
| or repr(object).
| encoding defaults to sys.getdefaultencoding().
| errors defaults to 'strict'.

>>> d = b'abcd'
>>> type(d)
<class 'bytes'>
>>> print(d)
b'abcd'
>>> len(d)
4
>>> m = str(d)
>>> type(m)
<class 'str'>
>>> print(m)
b'abcd'
>>> len(m)
7
>>> m.encode()
b"b'abcd'"
>>>
>>> m = str(d, encoding='utf-8')
>>> type(m)
<class 'str'>
>>> print(m)
abcd
>>> len(m)
4
>>>

help(str) 中提到“编码默认为 sys.getdefaultencoding()”,str(d) 仍然会转换带有 b'' 的字符串。请注意,字符串的长度现在为 7。问题是,

  1. 为什么需要显式指定默认编码才能使字节字符串正确
  2. 如何返回字节 - 新类型是字符串。 (对字符串进行编码将添加额外的 b)
  3. 有没有办法让 pylint 捕获/警告这个问题。

最佳答案

用于 bytes

str() 与用于 bytesrepr() 相同,完全适用于这是你最终不会滥用它的原因。这是一个更复杂的示例,其中源字符串是表情符号。

>>> s = "😸"
>>> len(s)
1 # One codepoint.
>>> b = s.encode("utf-8")
>>> len(b)
4 # Four bytes.
>>> print(b)
b'\xf0\x9f\x98\xb8' # Repr of the bytes, not to be interpreted.
>>> print(repr(b))
b'\xf0\x9f\x98\xb8' # Same as above!
>>> s2 = b.decode("utf-8") # Decode back to string from bytes.
>>> s == s2
True
>>>

也就是说,使用str.encode()从字符串中获取字节,bytes.decode()从字节中获取字符串。

关于python - 为什么 Python3 str(bytes) 转换为文字字符串 b'<str>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63129320/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com