Python Language String function - str() and repr()


Example

There are two functions that can be used to obtain a readable representation of an object.

repr(x) calls x.__repr__(): a representation of x. eval will usually convert the result of this function back to the original object.

str(x) calls x.__str__(): a human-readable string that describes the object. This may elide some technical detail.


repr()

For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(). Otherwise, the representation is a string enclosed in angle brackets that contains the name of the type of the object along with additional information. This often includes the name and address of the object.

str()

For strings, this returns the string itself. The difference between this and repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(). Rather, its goal is to return a printable or 'human readable' string. If no argument is given, this returns the empty string, ''.


Example 1:

s = """w'o"w"""
repr(s) # Output: '\'w\\\'o"w\''  
str(s)  # Output: 'w\'o"w'
eval(str(s)) == s  # Gives a SyntaxError 
eval(repr(s)) == s # Output: True

Example 2:

import datetime
today = datetime.datetime.now()
str(today)  # Output: '2016-09-15 06:58:46.915000'
repr(today) # Output: 'datetime.datetime(2016, 9, 15, 6, 58, 46, 915000)'

When writing a class, you can override these methods to do whatever you want:

class Represent(object):

    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return "Represent(x={},y=\"{}\")".format(self.x, self.y)

    def __str__(self):
        return "Representing x as {} and y as {}".format(self.x, self.y)

Using the above class we can see the results:

r = Represent(1, "Hopper")
print(r)  # prints __str__
print(r.__repr__)  # prints __repr__: '<bound method Represent.__repr__ of Represent(x=1,y="Hopper")>'
rep = r.__repr__()  # sets the execution of __repr__ to a new variable
print(rep)  # prints 'Represent(x=1,y="Hopper")'
r2 = eval(rep) # evaluates rep
print(r2)  # prints __str__ from new object
print(r2 == r)  # prints 'False' because they are different objects