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?
repr
should return the Python "object representation" that evaluates to such object, as applicable. This is why the string is quoted when usingrepr
: soeval(repr(someStr)) == someStr
should is true (it would also have nicely escaped unprintable and control characters). It (repr
and reprlib) is useful for debugging and exploring objects, but should generally not be used for end-user output. – Keroprint str(s)
andprint repr(s)
and you might find it more enlightening. – Nookrepr()
may be giving you a higher precision, but not necessarily a higher accuracy. It does show more digits, but because of typical floating point limitations, the value shown bystr()
may be better. Comparerepr(sum(0.1 for i in range(9)))
andstr(sum(0.1 for i in range(9)))
. On the other hand,str()
will hide the inherent inaccuracy from you, which confuses people who wonder whysum(0.1 for i in range(9)) == 0.9
returnsFalse
... – Hiphuggers