0

Here is some code that I've found and would like for someone to explain.

If I assign a string to the variable y, evaluate it with the eval function and assign the content to the variable y2, the interpreter returns true.

>>> y = 'a string'
>>> y2 = eval(repr(y))
>>> y == y2
>>> True

Where as using str(y) in this fashion:

>>> eval(str(y))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1
a string
       ^
SyntaxError: unexpected EOF while parsing

is not allowed. Why is that?

Luis Averhoff
  • 385
  • 6
  • 22

1 Answers1

5

str() just returns the string itself, it doesn't put quotes around it like repr() does.

y2 = eval(repr(y))

is equivalent to:

y2 = 'a string'

Since repr() adds quotes, this is valid.

y2 = eval(str(y))

is equivalent to:

y2 = a string

which is obviously nonsense because there are no quotes.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • 3
    @Luis see the docs for [repr](https://docs.python.org/2/library/functions.html#repr) specfically the part that says: *For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()* and compare that to [str](https://docs.python.org/2/library/functions.html#str) which says: *[...]The difference with repr(object) is that str(object) does not always attempt to return a string that is acceptable to eval(); its goal is to return a printable string[...] ''.* – Jon Clements May 19 '15 at 01:46