-2

I'm trying to run the command:

'"Isn\'t," she said.'

The output is: "Isn\'t," she said.

Why the output is not: "Isn't," she said.

Anyone knows what's the rule for this? Thanks

That1Guy
  • 7,075
  • 4
  • 47
  • 59
Roger
  • 23
  • 2

2 Answers2

4

You're seeing the difference between the two different ways of representing an object (repr and str).

>>> '"Isn\'t," she said.'
'"Isn\'t," she said.'
>>> print '"Isn\'t," she said.'
"Isn't," she said.

In the first case, python defaults to using repr -- however, the print function/statement uses str implicitly. Note that the major difference between these two methods is suggested in the Data Model for object.__repr__:

If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment).

In other words, you could use eval(repr('"Isn\'t," she said.')) and it will work. (This behavior isn't guaranteed for all objects, merely suggested. Since strings are such simple objects it works). However, eval(str('"Isn\'t," she said.')) won't work because you'll have quoting issues.

mgilson
  • 300,191
  • 65
  • 633
  • 696
  • +1, that's smart -- much more likely this than my answer. – jedwards Jun 19 '13 at 19:03
  • Yes, eval(str('"Isn\'t," she said.')) won't work as you said. However, what's really going with the quoting issues? the backslash works in other cases, for exmaple: '"Isn\"t," she said.' Is there any hidden rule for the backslash? – Roger Jun 19 '13 at 19:19
  • @Roger -- when python calls `repr` on a string, it adds a single quote in the beginning and at the end of the string and escapes any single quotes in the string. It's equivalent to `"'"+s.encode('string_escape')+"'"` – mgilson Jun 19 '13 at 19:33
  • Thanks! The above explanation is really clear! – Roger Jun 19 '13 at 19:50
0

The only thing I can think of is that you're using a raw string, which leaves backslashes in the string and doesn't interpret them as escape characters.

print('"Isn\'t," she said.')
>>> "Isn't," she said.

print(r'"Isn\'t," she said.')
>>> "Isn\'t," she said.
jedwards
  • 29,432
  • 3
  • 65
  • 92
  • no, I didn't use raw string and I'm pretty sure there is no 'r' before the string. In other cases, it works as it should. That's what confused me. It's in Python 3.3.2, is it related to the Python version. – Roger Jun 19 '13 at 19:08