Friday, March 6, 2015

Python: Differences between str() vs repr()

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)

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

Note the number of digits after decimal point, being represented for floating-point values,by both of them.
>>> str(1.0/7.0)
>>> repr(1.0/7.0)

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)
>>> print repr(s)

Initiating static local HTTP Server using different scripting languages

Initiating HTTP Server using different scripting languages ---------------------------------------------------------- Python -------...