我对数据类型和 UTF-8 编码很困惑。幕后究竟发生了什么?我在 Python 3 中读取没有定界符的困惑 JSON 数据(数据有时有日文/中文字符)。
我正在读取数据:
url = "http://localhost:8001"
data = urllib.request.urlopen(url).read()
type(data)
此时它返回 bytes
然后我要一个字母一个字母的读
for letter in data:
type(letter)
它返回给我的字母现在是一个整数。为什么它是一个字节,现在是一个整数? 附言我知道我得到的整数代表字符的十进制表示。但是这种来回跳跃让我感到困惑。
附言我也找不到 for-loop 的官方文档。有吗?
谢谢。
最佳答案
按照 Padraic Cunningham 的建议解码数据应该可行:
data = urllib.request.urlopen(url).read().decode("utf-8")
您还要求提供 for 循环的官方文档。我不确定你是否指的是 this或者您正在谈论 data
的迭代行为。
bytes
的迭代行为如所述 here :
Since bytes objects are sequences of integers (akin to a tuple), for a bytes object b, b[0] will be an integer, while b[0:1] will be a bytes object of length 1. (This contrasts with text strings, where both indexing and slicing will produce a string of length 1)
没有足够的代表将其作为对先前答案的评论发布,很抱歉。
关于python - Python 3 中 for 循环的数据类型和文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38014233/