<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 loop':
中操作此 str
for ID in response:
'response' 不是按行读取,而是按字符读取。
我打算将 'response' 的每一行放入列表的单个元素中。现在我必须在文件中写入响应并使用 'open' 获取可以在 'for loop'.
中使用的 <type 'str'>
字符串
没有区别。 Python 在 python 2 (Types are written like this: <type 'int'>
.) and python 3 (Types are written like this: <class 'int'>
.) 之间更改了 type
个对象的文本表示。在python2和3中,类型对象的类型都是,嗯,类型:
python 2
>>> type(type('a'))
<type 'type'>
python 3
>>> type(type('a'))
<class 'type'>
这就是更改的原因...字符串表示清楚地表明类型是 class。
至于你剩下的问题,
for ID in response:
response
是一个字符串,枚举它给出了字符串中的字符。根据您可能想要使用的响应类型和 HTML、JSON 或其他解析器将其转换为 python 对象。
正如评论者所提到的。在 python3:
>>>st = 'Hello Stack!'
>>>type(st)
<class 'str'>
但是在python2:
>>>st = 'Hello Stack!'
>>>type(st)
<type 'str'>
所以您看到的行为完全是意料之中的。至于遍历一个字符串,一个 for 循环遍历一个字符串将一个字符一个字符地遍历该字符串。如果你想遍历字符串中的每一行,你通常会做一些像 split on \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
以防你和我在 Jupyter
中遇到同样的困惑
使用 type("hi")
会给你 str
。
虽然使用 print(type('hi'))
会给你 <class 'str'>
反正都是一样的!
#python3
我是 python 的新手。我对 <class 'str'>
感到困惑。
我通过使用得到了一个 str:
response = urllib.request.urlopen(req).read().decode()
'response'的类型是<class 'str'>
,不是<type 'str'>
。
当我尝试在 'for loop':
for ID in response:
'response' 不是按行读取,而是按字符读取。 我打算将 'response' 的每一行放入列表的单个元素中。现在我必须在文件中写入响应并使用 'open' 获取可以在 'for loop'.
中使用的<type 'str'>
字符串
没有区别。 Python 在 python 2 (Types are written like this: <type 'int'>
.) and python 3 (Types are written like this: <class 'int'>
.) 之间更改了 type
个对象的文本表示。在python2和3中,类型对象的类型都是,嗯,类型:
python 2
>>> type(type('a'))
<type 'type'>
python 3
>>> type(type('a'))
<class 'type'>
这就是更改的原因...字符串表示清楚地表明类型是 class。
至于你剩下的问题,
for ID in response:
response
是一个字符串,枚举它给出了字符串中的字符。根据您可能想要使用的响应类型和 HTML、JSON 或其他解析器将其转换为 python 对象。
正如评论者所提到的。在 python3:
>>>st = 'Hello Stack!'
>>>type(st)
<class 'str'>
但是在python2:
>>>st = 'Hello Stack!'
>>>type(st)
<type 'str'>
所以您看到的行为完全是意料之中的。至于遍历一个字符串,一个 for 循环遍历一个字符串将一个字符一个字符地遍历该字符串。如果你想遍历字符串中的每一行,你通常会做一些像 split on \n
或一些设计用于在 URL 响应中的行分隔符上拆分的正则表达式。下面是 split
response = urllib.request.urlopen(req).read().decode()
lines = response.split('\n')
for x in lines:
st = x.strip()
# do some processing on st
以防你和我在 Jupyter
使用 type("hi")
会给你 str
。
虽然使用 print(type('hi'))
会给你 <class 'str'>
反正都是一样的!
#python3