使用str()将bytes转换为字符串后为何保留b标识与引号?
str(bytes) retain the b'...' notation? Great question! Let's break this down in plain terms:
When you use str() on a bytes object in Python, you're not actually decoding the byte sequence into human-readable text. Instead, str() returns the official string representation of the bytes object—this is exactly the output you'd see if you just typed the variable name into a Python interactive shell. The b'...' syntax is part of that representation to explicitly signal "this was originally a bytes object".
Let's walk through your example to make it clearer:
a = b'Hello World' # Using str() gives the string description of the bytes object b = str(a) print(b) # Output: b'Hello World' type(b) # <class 'str'>
The correct way to convert bytes to a string
To actually turn the raw byte sequence into a proper text string, you need to decode the bytes using the appropriate character encoding (UTF-8 is the default and works for most modern text cases):
a = b'Hello World' # Decode bytes to string (default encoding is UTF-8) b = a.decode() # Or explicitly specify the encoding if you need to: # b = a.decode('utf-8') print(b) # Output: Hello World type(b) # <class 'str'>
As a quick side tip, if you ever need to convert a string back to bytes, use the encode() method on the string:
s = 'Hello World' b = s.encode() # Defaults to UTF-8 type(b) # <class 'bytes'>
To wrap it up: str(bytes) gives you a string that describes the bytes object, while bytes.decode() translates the raw bytes into meaningful, human-readable text.
内容的提问来源于stack exchange,提问作者Xantium

