what is the difference between str()
and repr()
functions in python 2.7.5?
Explanation on python.org:
The
str()
function is meant to return representations of values which are fairly human-readable, whilerepr()
is meant to generate representations which can be read by the interpreter (or will force aSyntaxError
if there is no equivalent syntax)
But it wasn't clear for me.
some examples:
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'" # repr is giving an extra double quotes
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285' # repr is giving value with more precision
so I want to know the following
- When should I use
str()
and when should I userepr()
? - In which cases I can use either of them?
- What can
str()
do whichrepr()
can't? - What can
repr()
do whichstr()
can't?