Question

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

Was it helpful?

Solution

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.

OTHER TIPS

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top