Quoting quotes

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Feb 26 15:04:35 CET 2010


On Fri, 26 Feb 2010 13:29:04 +0100, candide wrote:

> But the first method doesn't run correctly :
> 
> 
>>>> print """The play "All's Well That Ends Well""""
>   File "<stdin>", line 1
>     print """The play "All's Well That Ends Well""""
>                                                    ^
> SyntaxError: EOL while scanning single-quoted string
>>>>
>>>>
> 
> Any comment ?

Of course not. Quotes can't be nested, so the first time the parser hits 
three quote marks, you have reached the end of the string. You then open 
a new string with a single quote mark, and then fail to close it. Hence 
the EOL while scanning a single-quoted string.

There are many solutions. Here are four:

>>> print """The play "All's Well That Ends Well\""""
The play "All's Well That Ends Well"
>>> print '''The play "All's Well That Ends Well"'''
The play "All's Well That Ends Well"
>>> print 'The play "All\'s Well That Ends Well"'
The play "All's Well That Ends Well"
>>> print 'The play "All' "'" 's Well That Ends Well"'
The play "All's Well That Ends Well"

-- 
Steven



More information about the Python-list mailing list