Build and previous answers and some more examples. When used correctly, the difference between str and repr is clear. In short, repr should return a string that can be copied to restore the exact state of the object, while str is useful for logging and observing debugging results. Here are some examples to see different results for some well-known libraries.
Datetime
print repr(datetime.now()) #datetime.datetime(2017, 12, 12, 18, 49, 27, 134411) print str(datetime.now()) #2017-12-12 18:49:27.134452
str is good for printing to a log file, where as repr can be reassigned if you want to run it directly or upload it as commands to a file.
x = datetime.datetime(2017, 12, 12, 18, 49, 27, 134411)
Numpy
print repr(np.array([1,2,3,4,5])) #array([1, 2, 3, 4, 5]) print str(np.array([1,2,3,4,5])) #[1 2 3 4 5]
in Numpy repr again directly expendable.
Custom Example Vector3
class Vector3(object): def __init__(self, args): self.x = args[0] self.y = args[1] self.z = args[2] def __str__(self): return "x: {0}, y: {1}, z: {2}".format(self.x, self.y, self.z) def __repr__(self): return "Vector3([{0},{1},{2}])".format(self.x, self.y, self.z)
In this example, repr again returns a string that can be directly used / executed, while str more useful as debug output.
v = Vector3([1,2,3]) print str(v)
One thing to keep in mind if str not defined, but repr , str will automatically call repr . So it is always good to at least define repr