【问题标题】:What is the difference between <class 'str'> and <type 'str'><class 'str'> 和 <type 'str'> 有什么区别
【发布时间】:2017-06-22 05:35:54
【问题描述】:

我是 python 新手。我对&lt;class 'str'&gt; 感到困惑。 我得到了一个 str 通过使用:

response = urllib.request.urlopen(req).read().decode()

“响应”的类型是&lt;class 'str'&gt;,而不是&lt;type 'str'&gt;。 当我尝试在“for循环”中操作这个str时:

for ID in response: 

“响应”不是按行读取,而是按字符读取。 我打算将每一行“响应”放入列表的单个元素中。现在我必须将响应写入一个文件并使用“打开”来获取我可以在“for循环”中使用的&lt;type 'str'&gt;字符串。

【问题讨论】:

  • 您使用的是 Python 2 还是 Python 3?
  • response = urllib.request.urlopen(req)?
  • Python 3. lib 没问题。

标签: python types decode urllib


【解决方案1】:

如果你和我在Jupyter中遇到的一样困惑

使用type("hi") 会得到str

在使用print(type('hi')) 时会给你&lt;class 'str'&gt; 反正都是一样的!

#python3

【讨论】:

    【解决方案2】:

    没有区别。 Python 在 python 2 (Types are written like this: &lt;type 'int'&gt;.) 和 python 3 (Types are written like this: &lt;class 'int'&gt;.) 之间更改了 type 对象的文本表示。在python 2和3中,type对象的类型都是,嗯,类型:

    蟒蛇2

    >>> type(type('a'))
    <type 'type'>
    

    蟒蛇3

    >>> type(type('a'))
    <class 'type'>
    

    这就是改变的原因......字符串表示清楚地表明类型是一个类。

    至于剩下的问题,

    for ID in response:
    

    response 是一个字符串,枚举它会给出字符串中的字符。根据您可能想要使用的响应类型以及 HTML、JSON 或其他解析器将其转换为 python 对象。

    【讨论】:

    • 你是对的。这就是 Python2 和 3 的区别。感谢您的回答。
    【解决方案3】:

    正如评论者所说。在python3中:

    >>>st = 'Hello Stack!'
    >>>type(st)
    <class 'str'>
    

    但是在python2中:

    >>>st = 'Hello Stack!'
    >>>type(st)
    <type 'str'>
    

    因此,您看到的行为完全是意料之中的。至于对字符串进行循环,对字符串的 for 循环将逐个字符地遍历字符串。如果你想遍历字符串中的每一行,你通常会在\n 上进行拆分,或者在 URL 响应中的行分隔符上进行一些正则表达式。下面是split产生的列表的简单for循环

    response = urllib.request.urlopen(req).read().decode()
    lines = response.split('\n')
    for x in lines:
        st = x.strip()
        # do some processing on st
    

    【讨论】:

    • 太棒了!我花了 10 多个小时在互联网上尝试了很多示例,但没有任何效果。这非常适合拆分和遍历列表。谢谢!