Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between <class 'str'> and <type '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()

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

for ID in response: 

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'.

like image 315
dom free Avatar asked Feb 05 '17 02:02

dom free


People also ask

What does type STR mean in Python?

Python has a built-in string class named "str" with many handy features (there is an older module named "string" which you should not use). String literals can be enclosed by either double or single quotes, although single quotes are more commonly used.

What is the purpose of __ Str__ method?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object.

What is the difference between STR and string in Python?

"string" is a module that provides string handling functions, str is a built-in function that converts an object to a string representation.

What is the purpose of defining the functions __ str __ and __ repr __ within a class how are the two functions different?

The print statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.


1 Answers

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,

for ID in 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.

like image 185
tdelaney Avatar answered Sep 21 '22 20:09

tdelaney