繁体   English   中英

之间有什么区别<class 'str'>和<type 'str'>

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

如果你有我在JupyterJupyter的同样困惑

使用type("hi")会给你str

虽然使用print(type('hi'))会给你<class 'str'>无论如何,两者都是一样的!

在此处输入图片说明

#python3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM