The rule of literal string

Chris Rebert clp at rebertia.com
Wed Dec 17 06:44:41 CET 2008


On Tue, Dec 16, 2008 at 9:32 PM, Li Han <lihang9999 at gmail.com> wrote:
> Hi! I just began to read the tutorial of python3.0 and I just can't
> figure out the rule of literal string. There is a example in the
> tuotrial:
>>>> '"Isn\'t," she said.'
> '"Isn\'t," she said.'
> It is not what I want, I just want '"Isn't," she said.' be printed,
> why the backslash failed?
> These don't work at all:
>>>> '''"Isn't," she said.'''
> '"Isn\'t," she said.'
>>>> r"Isn't," she said.
> SyntaxError: invalid syntax (<pyshell#6>, line 1)
>>>> r'"Isn't," she said.'
> SyntaxError: invalid syntax (<pyshell#7>, line 1)
> I have tried to solve it until my brain damaged and now I need to
> sleep.

You need to print() the string. Otherwise, the interpreter does an
implicit repr() on the string, causing it to output a string literal
equivalent to the string, essentially doing print(repr(your_string)).
To explain what repr() does, consider the following identity:
eval(repr(your_string)) == your_string
Notice how the outer set of quotes is still present in the output you
got. Using print() explicitly causes repr() not to be called, thus the
escape backslashes aren't shown and neither are the surrounding
quotes.

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list