repr(): evaluatable string representation of an object (can "eval()"
it, meaning it is a string representation that evaluates to a Python
object)
In other words:
>>> x = 'foo'
>>> repr(x)
"'foo'"
Questions:
- Why do I get the double quotes when I do
repr(x)? (I don't get them when I dostr(x)) - Why do I get
'foo'when I doeval("'foo'")and not x which is the object?
So the name
xis attached to'foo'string. When you call for examplerepr(x)the interpreter puts'foo'instead ofxand then callsrepr('foo').repractually calls a magic method__repr__ofx, which gives the string containing the representation of the value'foo'assigned tox. So it returns'foo'inside the string""resulting in"'foo'". The idea ofrepris to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument torepr.When we call
eval("'foo'"), it's the same as we type'foo'in the interpreter. It's as we directly type the contents of the outer string""in the interpreter.If we call
eval('foo'), it's the same as we typefooin the interpreter. But there is nofoovariable available and an exception is raised.stris just the string representation of the object (remember,xvariable refers to'foo'), so this function returns string.String representation of integer
5is'5'.And string representation of string
'foo'is the same string'foo'.