You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用str()将bytes转换为字符串后为何保留b标识与引号?

Why does 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:10:53