assigning multi-line strings to variables
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Thu Apr 29 23:21:44 EDT 2010
On Fri, 30 Apr 2010 05:41:26 +1000, Lie Ryan wrote:
> On 04/29/10 20:40, Gregory Ewing wrote:
>> Lie Ryan wrote:
>>> No, the implicit concatenation is there because Python didn't always
>>> have triple quoted string. Nowadays it's an artifact and triple quoted
>>> string is much preferred.
>>
>> I don't agree. I often use implicit concatenation when I'm writing a
>> format string that won't fit on one source line, because it allows me
>> to fit it into the surrounding indentation structure without
>> introducing unwanted spaces into the string.
>>
>> Both tecnhiques have their places.
>>
>>
> That statement should be quantified with "for large chunks of text".
> Format string is typically 2-3 lines at most, not enough to qualify as
> large chunk.
No it shouldn't. It applies equally for two lines or two hundred lines.
You seem to have missed that these are NOT equivalent:
"""abcd
efgh"""
"abcd"\
"efgh"
To avoid the ugly backslash, you can use Python's implicit line
continuation inside brackets. This is especially handy since you often
use brackets for function calls:
len(
"this is a very long string that won't fit"
" on a single line in the source code, but"
" must be a single line string, which is why"
" a triple-quoted string is not appropriate.")
To get the same result using triple-quoted strings, you would need to do
this:
len(
"""this is a very long string that won't fit\
on a single line in the source code, but\
must be a single line string, which is why\
a triple-quoted string is not appropriate.""")
but the second is risky, because an invisible whitespace character
following the backslash will introduce bugs into your code:
>>> assert len(
... """abc\
... def""") == 6
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
AssertionError
--
Steven
More information about the Python-list
mailing list