assigning multi-line strings to variables

Lie Ryan lie.1296 at gmail.com
Thu Apr 29 16:04:25 EDT 2010


On 04/29/10 16:34, Steven D'Aprano wrote:
> On Thu, 29 Apr 2010 02:16:46 +0100, MRAB wrote:
> 
>> Steven D'Aprano wrote:
>>> On Thu, 29 Apr 2010 06:17:42 +1000, Lie Ryan wrote:
>>>
>>>>> Consider that the concatenation language feature probably is there
>>>>> because it's useful (e.g. it preserves indentation and allows per
>>>>> line comments).
>>>> No, the implicit concatenation is there because Python didn't always
>>>> have triple quoted string.
>>>
>>> Do you have a source for that?
>>>
>>> Both triple-quoted strings and implicit concatenation go back to at
>>> least Python 1.4:
>>>
>>> http://docs.python.org/release/1.4/tut/node71.html
>>> http://docs.python.org/release/1.4/tut/node70.html
>>>
>> The page here:
>>
>>      http://svn.python.org/projects/python/branches/py3k/Misc/HISTORY
>>
>> says release 1.0.2 (4 May 1994).
> 
> Yes, it says:
> 
>     * String literals follow Standard C rules: they may be continued 
>     on the next line using a backslash; adjacent literals are 
>     concatenated at compile time.
> 
>     * A new kind of string literals, surrounded by triple quotes 
>     (""" or '''), can be continued on the next line without a 
>     backslash.
> 
> 
> These are adjacent entries in the same release. That's pretty good 
> evidence that both implicit concatenation and triple quotes were 
> introduced at the same time.

Yes, apparently my statement that implicit concatenation is an artifact
is erroneous but it doesn't make the important points less true, that
implicit concatenation is not suitable for integrating large chunk of
text into source code.

And if you do care about the two extra newlines, you can add two
backslashes:

s = """\
...
insert large chunks
...\
"""

which is a constant-time preformatting compared to prepending and
appending every line with quotes, which is O(n) (and we're talking about
the oh-so-expensive programmer's time here).

Ben Finney also showed the trick to let a large chunk to appear indented
and stripping the indenting at runtime in another thread (which is
actually rarely needed since, since as I previously said, huge chunk of
text is usually global-level variable; though the trick does come handy
sometimes).



More information about the Python-list mailing list