Both str() and repr() methods in python are used for string representation of a string. But there are little difference between them.
>>> x=”Hello World”
>>> print(x.__str__()) ## More readable for end-user
Hello World
>>> print(x.__repr__()) ## More useful for developer and debugging
‘Hello World’
__str__
- Make object more readable
- Invoked by str, print ..etc.
- str() function by default uses __str__(). If __str__() not found, str() uses __repr__()
class C1:
def __init__(self):
pass
def __repr__(self):
return “{}”.format(self.__class__.__name__)
obj=C1()
print(obj)
print(str(obj))
4. Generates output for end-user
5. Informal string representation
6. Cannot reconstruct object
>>> str1 = “Hi”
>>> str(str1)
‘Hi’
>>> str2 = eval (str(str1))
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
File “<string>”, line 1, in <module>
NameError: name ‘Hi’ is not defined
>>>
__repr__
- Invoked when you simply write object’s name on interactive python console and press enter
- Invoked by repr() function
class C1:
def __init__(self):
pass
def __repr__(self):
return “{}”.format(self.__class__.__name__)
obj=C1()
print(obj) # fallback to __repr__ if no __str__ found
print(repr(obj))
Output:
C1
C1
3. If no __repr__ are there in a class, repr() will simply print the object representation
class C1:
def __init__(self):
pass
def __str__(self):
return “{}”.format(self.__class__.__name__)
obj=C1()
print(obj)
print(repr(obj))
Output:
C1
<__main__.C1 object at 0x7f482dfe8070>
4. Generates output for developer and debugging purposes
5. it shows official string representation
6. We can reconstruct object
>>> str1 = “Hi”
>>> repr(str1)
“‘Hi’”
>>> str2 = eval (repr(str1))
>>> str1 == str2
True