我是python的新手。我被<class 'str'>
搞糊涂了。我通过使用以下命令获得了一个str:
response = urllib.request.urlopen(req).read().decode()
“response”的类型是<class 'str'>
,而不是<type 'str'>
。当我试图在'for loop‘中操作这个字符串时:
for ID in response:
“响应”不是按行读取的,而是按字符读取的。我打算将“响应”的每一行都放入列表的各个元素中。现在,我必须将响应写在一个文件中,并使用'open‘来获取一个可以在'for loop’中使用的<type 'str'>
字符串。
发布于 2017-02-05 03:31:26
正如评论者所提到的。在python3中:
>>>st = 'Hello Stack!'
>>>type(st)
<class 'str'>
但在python2中:
>>>st = 'Hello Stack!'
>>>type(st)
<type 'str'>
因此,您看到的行为完全是意料之中的。至于对字符串的循环,字符串上的for循环将逐个字符地迭代字符串。如果要遍历字符串中的每一行,通常需要对\n
执行split或一些正则表达式,该正则表达式旨在拆分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
发布于 2017-02-05 03:31:13
这是没有区别的。Python在Python2 (Types are written like this: .)和Python3 (Types are written like this: .)之间更改了type
对象的文本表示。在python 2和3中,类型对象的类型都是,嗯,类型:
python 2
>>> type(type('a'))
<type 'type'>
python 3
>>> type(type('a'))
<class 'type'>
这就是改变的原因。字符串表示清楚地表明该类型是一个类。
至于你剩下的问题
for ID in response:
response
是一个字符串,枚举它会得到字符串中的字符。根据您可能要使用的响应类型以及HTML、JSON或其他解析器将其转换为python对象。
发布于 2021-11-01 12:25:19
如果你有和我在Jupyter
中一样的困惑
使用type("hi")
将为您提供str
。
虽然使用print(type('hi'))
会给你带来<class 'str'>
,但两者是一样的!
#python3
https://stackoverflow.com/questions/42048107
复制相似问题