Triple quoted string in exec function ?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Jan 2 09:24:39 EST 2009


On Fri, 02 Jan 2009 14:39:25 +0100, Stef Mientki wrote:

> thanks for all the answers,
> but I still don't understand it yet :-( So maybe someone could explain
> why the next few lines of code don't work:
> 
> Code = ''
> Code += """multiline comment
> and more lines"""
> exec ( Code )


You don't actually tell us what you expect to happen, so I'm going to 
take a wild guess. You are expecting that the contents of Code above 
should be a triple-quoted string, which Python treats as a comment when 
it is on its own (unless it is a doc string).

A clue as to what is going on:

>>> s = "x = 1"
>>> print s
x = 1
>>> exec s
>>> x
1

Notice that even though the string s is created with delimiters ", the 
quote marks are not part of the string. Whether you use delimiters " ' 
''' or """ doesn't matter, the delimiters are not part of the string. If 
you want quote marks *inside* the string, you need to include them as 
characters, not as delimiters:

>>> s = "y = "  # using " as delimiters
>>> s += 'abc'  # using ' as delimiters
>>> print s  # no quotes inside s
y = abc
>>> exec s
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'abc' is not defined

>>> s = "y = "
>>> s += '"abc"'  # quotes inside the string
>>> print s  # includes quotes inside s
y = "abc"
>>> exec s
>>> y
'abc'


The fact that your earlier example used """ as delimiters instead of " is 
irrelevant. The delimiters are not part of the string, and so aren't seen 
by exec. There's no problem with exec and triple-quoted strings. You're 
just not giving it a triple-quoted string to work with.


Another thing, you wrote:

Code = ''
Code += """multiline comment
and more lines"""

That's a little like saying:

x = 0
x += 1

instead of just x = 1. Except that in general, string concatenation is 
potentially MUCH MUCH MUCH slower than addition. (If you haven't noticed 
the slow down, you're lucky you haven't hit the right circumstances.)


s = """multiline comment
and more lines"""

makes a string s that starts with the letter m:

>>> print s
multiline comment
and more lines

That's no different from any other string delimiters. The delimiters are 
never part of the string.

You want the string to start with three quotation marks, not m, so you 
have to include the quote marks inside the string. To do that, you need 
to use two different quote delimiters:

>>> s = """'''multiline comment
... and more lines'''"""
>>> print s
'''multiline comment
and more lines'''
>>> exec s
>>>

Works perfectly.



-- 
Steven



More information about the Python-list mailing list