< class'str'>和有什么区别?和< type'str'> [英] What is the difference between <class 'str'> and <type 'str'>

查看:771
本文介绍了< class'str'>和有什么区别?和< type'str'>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是python的新手。我对< class str> 感到困惑。
我使用以下方法得到了str:

I am new to python. I'm confused by the <class 'str'>. I got a str by using:

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

响应的类型为< class'str '> ,而不是< type'str'>
当我尝试在 for循环中操纵​​此str时:

The type of 'response' is <class 'str'>, not <type 'str'>. When I try to manipulate this str in 'for loop':

for ID in response: 

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

The 'response' is read NOT by line, BUT by character. I intend to put every line of 'response' into individual element of a list. Now I have to write the response in a file and use 'open' to get a string of <type 'str'> that I can use in 'for loop'.

推荐答案

如评论者所述。在python3中:

As mentioned by the commenters. In python3:

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

但是在python2中:

But in python2:

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

因此,完全可以预期您所看到的行为。至于对字符串的循环,对字符串的for循环将逐个字符地迭代字符串。如果要遍历字符串中的每一行,通常可以在 \n 上执行split或设计用于在URL响应中的行分隔符上进行拆分的正则表达式。下面是一个简单的for循环,它由 split

So the behavior that you are seeing is entirely expected. As to looping over a string, a for loop over a string will iterate over the string character by character. If you want to iterate over each line in the string, you usually do something like split on \n or some regex designed to split on the line separators in the URL response. Below is a simple for loop over the list resulting from split

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

这篇关于&lt; class'str'&gt;和有什么区别?和&lt; type'str'&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆