I can write 'something '.strip()
and get something
in return or I can type str(8)
and get '8'
in return. Also, type ('a')
returns str
as the response. Is str
a function (which converted a numeric 8
to '8'
) or a class, which has methods such as strip()
, etc.?
It is a class, whose constructor can get any Python object, and attempts to convert that to a string according to rules built-in the language.
The first thing it tries to do is to call the __str__
method in the passed in object. If that does not exist, it tries to call the __repr__
method. Whatever is returned is used as the new built string.
However, str is trully the string class in Python, were all string methods are defined.
str
is a class. As seen in the documentation
str(8) # returns '8'
Is creating an object of type str
. It calls str
's constructor. Which in turn calls the objects __str__
function.
As suggested in the comments, you can take a closer look at what's happens using the type
keyword:
type(str) # <class 'type'>
type(str()) # <class 'str'>
type('Hello, World!') # <class 'str'>
type(8) # <class 'int'>
type(str(8)) # <class 'str'>
type(str().strip) # <class 'builtin_function_or_method'>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.