str() and repr()

Python - text strings

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. 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

import datetime

today = datetime.datetime.now()

# print() shows the same as str() except of the quotation marks

print(today)

2022-11-14 10:50:01.046192

# repr() gives a representation that can be computational analyzed

str(today)

'2022-11-14 10:50:01.046192'

repr(today)

'datetime.datetime(2022, 11, 14, 10, 50, 1, 46192)'



# ideally, repr() gives all information in form of valid code to reconstruct the object: eval(repr(x))==x

datetime.datetime(2022, 11, 14, 10, 50, 1, 46192)

datetime.datetime(2022, 11, 14, 10, 50, 1, 46192)

eval('datetime.datetime(2022, 11, 14, 10, 50, 1, 46192)')

datetime.datetime(2022, 11, 14, 10, 50, 1, 46192)


# 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