String Object Representation in Python
This question already has an answer here:
__str__
(usually read dunder, for double under) is an instance method that is called whenever you run str(<object>)
and returns the string representation of the object.
str(foo)
acts as a function trying to convert foo
into a string.
Note:
There is also a __repr__()
method which is fairly similar to __str__()
, the main difference being __repr__
should return an unambiguous string and __str__
is for a readable string. For a great response on the diffences between the two I'd suggest giving this answer a read.
__str__()
is a magic instance method that doee this: when you print a class instance variable with print()
, it will give you a string that can be modified by changing the returned string in the __str__()
method. There's probably a better explanation to it but I can show you with code:
class Thing:
def __init__(self):
pass
def __str__(self):
return "What do you want?" #always use return
a = Thing()
print(a)
OUTPUT:
What do you want?
str()
just converts a variable into a string type variable.
print(str(12.0))
OUTPUT:
'12.0'
You can confirm it is a string using the type()
function.
print(type(str(12.)))
I don't know the exact output of that but it will peobably have 'str'
in it.
上一篇: 在Python中获取数组的长度
下一篇: Python中的字符串对象表示