Both str() and repr() are used to represent strings in python.
But, there exists some differences in their representation.
str() return strings which ease human-reading.
repr() return string which can also the read by human-beings,
but its representation eases the machine.
Observe few differences below:
They differ in displaying the string
>>> s='Hello, world!!!!'
>>> str(s)
'Hello, world!!!!'
>>> repr(s)
"'Hello, world!!!!'"
Though both are representing the same string, they are not logically same.
>>> str(s)==repr(s)
False
But, str(repr()) and repr(str()), both are finally equal
>>> str(repr(s))
"'Hello, world!!!!'"
>>> repr(str(s))
"'Hello, world!!!!'"
>>> repr(str(s))==str(repr(s))
True
Note the number of digits after decimal point, being represented for floating-point values,by both of them.
>>> str(1.0/7.0)
'0.142857142857'
>>> repr(1.0/7.0)
'0.14285714285714285'
Observe the presence and absence of effect of escape sequences, in printing a str() and repr() based strings, respectively.
>>> s="Hello\nworld"
>>> print str(s)
Hello
world
>>> print repr(s)
'Hello\nworld'
Comments
Post a Comment