[英]What is the difference between <class 'str'> and <type 'str'>
我是python的新手。 我對<class 'str'>
感到困惑。 我通過使用得到了一個 str:
response = urllib.request.urlopen(req).read().decode()
'response' 的類型是<class 'str'>
,而不是<type 'str'>
。 當我嘗試在“for 循環”中操作此 str 時:
for ID in response:
“響應”不是按行讀取,而是按字符讀取。 我打算將每一行“響應”放入列表的單個元素中。 現在我必須將響應寫入文件並使用“open”來獲取我可以在“for循環”中使用的<type 'str'>
字符串。
沒有區別。 Python 在 python 2(類型寫成這樣: <type 'int'>
. )和 python 3 (類型寫成這樣: <class 'int'>
. )之間改變了type
對象的文本表示。 在python 2和3中,類型對象的類型都是,嗯,類型:
蟒蛇2
>>> type(type('a'))
<type 'type'>
蟒蛇 3
>>> type(type('a'))
<class 'type'>
這就是改變的原因……字符串表示清楚地表明類型是一個類。
至於你剩下的問題,
for ID in response:
response
是一個字符串,枚舉它會給出字符串中的字符。 根據您可能想要使用的響應類型以及將其轉換為 Python 對象的 HTML、JSON 或其他解析器。
正如評論者所說。 在python3中:
>>>st = 'Hello Stack!'
>>>type(st)
<class 'str'>
但是在python2中:
>>>st = 'Hello Stack!'
>>>type(st)
<type 'str'>
因此,您所看到的行為完全符合預期。 至於遍歷字符串,對字符串的 for 循環將逐個字符地遍歷字符串。 如果您想遍歷字符串中的每一行,您通常會執行諸如 split on \\n
或一些旨在在 URL 響應中的行分隔符上拆分的正則表達式之類的操作。 下面是一個簡單的 for 循環,遍歷由split
產生的列表
response = urllib.request.urlopen(req).read().decode()
lines = response.split('\n')
for x in lines:
st = x.strip()
# do some processing on st
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.