Skip to content Skip to sidebar Skip to footer

What Is The Difference Between And

I am new to python. I'm confused by the . I got a str by using: response = urllib.request.urlopen(req).read().decode() The type of 'response' is

Solution 1:

There is no difference. Python changed the text representation of type objects between python 2 (Types are written like this: <type 'int'>.) and python 3 (Types are written like this: <class 'int'>.). In both python 2 and 3, the type of the type object is, um, type:

python 2

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

python 3

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

And that's the reason for the change... the string representation makes it clear that the type is a class.

As for the rest of your problem,

forIDin response:

response is a string and enumerating it gives the characters in the string. Depending on the type of response you may want to use and HTML, JSON or other parser to turn it into python objects.

Solution 2:

As mentioned by the commenters. In python3:

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

But in python2:

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

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 inlines:
    st = x.strip()
    # do some processing on st

Solution 3:

In case you have the same confusing I got in Jupyter

Using type("hi") will give you str.

While using print(type('hi')) will give you <class 'str'> Anyway, both are the same!

enter image description here

#python3

Post a Comment for "What Is The Difference Between And "