[英]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.