Python in Detail: Repr
Welcome to the Repr lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We've seen the built-in
strfunction, which converts non-string values into strings. This lesson coversrepr, which also converts values into strings, but these strings are specifically meant for programmers. For some values, like integers,reprbehaves exactly likestr.>
repr(5)Result:
>
repr(42)Result:
'42'
For strings,
reprandstrbehave differently. Thestrof a string is exactly the same string, but thereprof a string contains quotes.>
repr("Hello")Result:
>
repr("Amir")Result:
"'Amir'"
>
(repr("Hello"), str("Hello"))Result:
("'Hello'", 'Hello')reprreturns the canonical or official representation of a value. Usually,reprreturns a string that gives us the original value when passed toeval. In other words,reprusually gives us valid Python code that will recreate the original value.>
eval(repr("Amir"))Result:
>
eval(repr("Amir")) == "Amir"Result:
True
The difference between
reprandstrmay seem minor at first, but it's important. For example,str(10),str("10"), andstr(Decimal(10))are all the same. When we print them to the console, we can't tell the difference.>
from decimal import Decimalprint("The value is:", str(10))print("The value is:", str("10"))print("The value is:", str(Decimal(10)))console output>
from decimal import Decimalstr(10) == str("10") == str(Decimal(10))Result:
True
This can cause problems when debugging. We might print a variable out with
str, see that it contains 10, and not understand why the code isn't working. The problem is that the we think the value is the integer10, but it's actually"10", or maybeDecimal(10). Those differences are hidden from us when usingstr.Now here's the
reprequivalent, where all three values are clearly distinct.>
from decimal import Decimalprint("The value was:", repr(10))print("The value was:", repr("10"))print("The value was:", repr(Decimal(10)))console output>
repr(10) == repr("10")Result:
False
Note that all of those
reprresults are legal Python syntax:Decimal('10')is the Python code to create that value.>
from decimal import DecimalDecimal('10') == eval(repr(Decimal('10')))Result:
True
Here's a summary of when to use
strvs.repr:strreturns an informal, and often imprecise, representation of a value. Thestr(...)may not clearly indicate the value's type, as we saw with integers vs. strings that happen to look like integers. We often usestrwhen showing data to users. Most users don't care about whether a value is an integer or aDecimal.repris a more precise and exact representation of the value. It should indicate the data type as well as its value, and ideally it should be a valid Python expression.repris intended for programmers, not users. We recommend usingreprwhenever you're debugging, generating logs, or generating reports intended for programmers.