String representation of Python objects

Feb 8, 2014

It is often necessary to provide string representation of objects. Application of this can be found in debugging, storing in a file, communication across the network, etc. Two builtin functions str() and repr() output string representation of Python objects. But how do they differ from each other ?

str() Returns an informal string representation of an object. Does not necessarily has to be a valid python expression.

repr() Returns a formal string representation, can be used as a valid python expression to reconstruct the object.

The member functions __str__() and __repr__() should be overriden to produce useful string representation of custom objects. These two functions are called inside str() and repr() respectievely. This is illustrated in the following example.

A class for entries in the periodic table:

class element :
    def __init__(self, a, m): = a ;
        self.atomic_mass = m ;

    def __str__(self):
        return "{0} has atomic mass {1}".format(, self.atomic_mass)

    def __repr__(self):
        return "element(\"{0}\", \"{1}\")".format(, self.atomic_mass)

Trying it out:

H = element("Hydrogen", 1.00794)
print H
print repr(H)
print eval(repr(H))

And the output is:

Hydrogen has atomic mass 1.00794
element("Hydrogen", "1.00794")
Hydrogen has atomic mass 1.00794