The str() STRing and repr() REPResentation built-in functions or the single back or reverse quote operator ( “ ) come in really handy if the need arises to either recreate an object through evaluation or obtain a human-readable view of the contents of objects, data values, object types, etc. To use these operations, a Python object is provided as an argument and some type of string representation of that object is returned.
In some examples below, we take some random Python types and convert them to their string representations.
>>> str(4.53-2j) '(4.53-2j)' >>> str(1) '1' >>> str(2e10) '20000000000.0' >>> str([0,5,9,9]) '[0, 5, 9, 9]' >>> repr([0,5,9,9]) '[0, 5, 9, 9]' >>> '[0,5,9,9]' '[0,5,9,9]'
Although all three are similar in nature and functionality, only repr() and “ do exactly the same thing, and using them will deliver the “official” string representation of an object that can be evaluated as a valid Python expression (using the eval() built-in function). In contrast, str() has the job of delivering a “printable” string representation of an object which may not necessarily be acceptable by eval(), but will look nice in a print statement.
The executive summary is that repr() is Python-friendly while str() produces manfriendly
output. However, with that said, because both types of string representations coincide so often, on many occasions all three return the exact same string.