python3中forloop的数据类型和文档

2024-05-03 19:29:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我对数据类型和UTF-8编码非常困惑。引擎盖下到底发生了什么?我在python3中读取了一个没有定界符的混乱JSON数据(数据有时有日语/中文字符)。你知道吗

我在读数据:

url = "http://localhost:8001"
data = urllib.request.urlopen(url).read()
type(data)

此时它返回字节

然后我想一个字母一个字母地读

for letter in data:
    type(letter)

它现在返回的字母是一个整数。为什么它是一个字节而现在是一个整数? P、 我知道我得到的整数代表字符的十进制表示。但是这种来回的跳跃让我很困惑。你知道吗

另外,我也找不到for loop的官方文档。有吗?你知道吗

谢谢你。你知道吗


Tags: 数据url编码fordata字节type字母
2条回答

按照Padraic Cunningham的建议对数据进行解码应该是可行的:

data = urllib.request.urlopen(url).read().decode("utf-8")

你还要求提供for循环的官方文档。我不确定您是指this还是指data的迭代行为。你知道吗

a 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)

没有足够的代表张贴它作为评论之前的答案,我很抱歉。你知道吗

您需要将bytes解码为str

In [12]: data = urllib.request.urlopen("http://stackoverflow.com/questions/38014233/data-types-and-documentation-for-for-loop-in-python-3/38014292#38014292").read()

In [13]: type(data)
Out[13]: bytes

In [14]: type(data.decode("utf-8"))
Out[14]: str

In [15]: data[0]
Out[15]: 60

In [16]: data.decode("utf-8")[0]
Out[16]: '<'

解码后,你会看到字符时,你循环和打印。urllib.request.urlopen(url).read()返回字节,由您将字节解码为str

相关问题 更多 >