input

import math
print(repr(math.pi))
print(str(math.pi))

output

3.141592653589793
3.141592653589793

could someone please tell me what the difference between

repr

and

str

is as the example on the documentation does not help as they both return the same figure?
surely it does something more complex?

repr(object)ΒΆ

Return a string containing a printable representation of an object. 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 together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__() method.

repr is supposed to evaluate same object as original when run through eval:

>>>print eval(repr(object)) == object
True

Str is human friendly output format for Human eyes. Often if there is not better format the str has simple definition:

repr = str

However it is often usefull to have fancier output available for reporting, for example for strings repr is quoted and str is not.

>>> eval(repr('Python'))
'Python'
>>> repr('Python')
"'Python'"
>>> str('Python')
'Python'
>>>

This repr rule however is not working with complicated or builtin objects:

>>> map
<class 'map'>
>>> repr(map)
"<class 'map'>"
>>> eval(repr(map))
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    eval(repr(map))
  File "<string>", line 1
    <class 'map'>
    ^
SyntaxError: invalid syntax
commented: very helpfull :) +1

The example in the Python32 docs elucidates that in earlier versions of Python here was a difference, the str() result was rounded off ...

import math
print(repr(math.pi))
print(str(math.pi))

'''
result (Python31 and earlier) -->
3.141592653589793
3.14159265359
result (Python32) -->
3.141592653589793
3.141592653589793
'''
commented: very helpfull thanks +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.