Strings‎ > ‎

str() and repr()

representation of objects

str(x)  gives a readable end-user output of an object, for example, str(x) is used by the command print()

repr(x) is an more exact and informative output (representation) useful for debugging as given by the command line of the interpreter. If  __repr__ is not defined, Python gives the type and memory as default output.

For many objects str(x) and repr(x) give (almost) the same output.
 

# example
#   print() shows the same as str() except of the quotation marks
#   repr() gives a representation that can be computational analysed
import datetime
today = datetime.datetime.now()
print(today)
2015-01-31 21:49:25.840500
str(today)
'2015-01-31 21:49:25.840500'
repr(today)
'datetime.datetime(2015, 1, 31, 21, 49, 25, 840500)'


# ideally, repr() gives all information in form of valid code to reconstruct the object: eval(repr(x))==x
>>> datetime.datetime(2015, 1, 15, 21, 49, 25, 840500)
datetime.datetime(2015, 1, 15, 21, 49, 25, 840500)
>>> eval('datetime.datetime(2015, 1, 15, 21, 49, 25, 840500)')
datetime.datetime(2015, 1, 15, 21, 49, 25, 840500)


# repr() can be helpful for debugging or logging as it provides more detailed information than print()
try:
    x=10/0
except ( FloatingPointError, ZeroDivisionError ) as err:
    print(err)
division by zero

try:
    x=10/0
except ( FloatingPointError, ZeroDivisionError ) as err:
    repr(err)
"ZeroDivisionError('division by zero',)"




read more
http://stackoverflow.com/questions/19331404/str-vs-repr-functions-in-python-2-7-5
http://satyajit.ranjeev.in/2012/03/14/python-repr-str.html