python - Python 3 中 for 循环的数据类型和文档

标签 python string python-3.x utf-8

我对数据类型和 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/

相关文章:

c++ - 如何将 IHTMLDocument2 ->get_body ->get_innerHTML 变成小写字符串?

python - QFrame边框不显示

python - 使用一个类同时作为装饰器和装饰器工厂进行操作

python - Groupby Sum 忽略几列

c# - 为什么我不能在字符串前使用@$ 前缀?

java - 将字符串传递给另一个类

python - Pyramid :从列表生成 json View

python-3.x - 无法使用 PyInstaller 错误创建 .exe 文件

python - Cefpython GetText() 函数

python - 无法在 Web 浏览器中从 python 打开 html 文件 - 改为用记事本打开