Hot to split string literals that will across two or more lines ?

Steve Holden steve at holdenweb.com
Tue Nov 22 13:38:15 EST 2005


Paul McGuire wrote:
> "Ben Finney" <bignose+hates-spam at benfinney.id.au> wrote in message
> news:dljic3$rpv$1 at rose.polar.local...
> 
>>Xiao Jianfeng <fdu.xiaojf at gmail.com> wrote:
>>
>>>I need to print a long sting, which is two long so it must expand
>>>two lines.
>>
>>How is this string being constructed in the source? If it exists as a
>>single long string, why must it be so long?
>>
>>Some techniques you may not be aware of:
>>
>>    >>> chunks = ["abc", "def", "ghi"]
>>    >>> s = ''.join(chunks)
>>    >>> print s
>>    abcdefghi
>>
>>    >>> s = "#" * 10
>>    >>> print s
>>    ##########
>>
>>You can, of course, modify the above so that they join or multiply to
>>create much longer strings.
>>
>>-- 
>> \                          "Everything is futile."  -- Marvin of Borg |
>>  `\                                                                   |
>>_o__)                                                                  |
>>Ben Finney
> 
> 
> Or for a large literal string:
> 
> """
> lots of text hundreds of characters long
> more text on another line but we really don't want any line breaks
> in our final string
> so we replace newlines in this multiline string
> with an empty string thus
> """.replace('\n','')
> 

Of course there's also the alternative of escaping the newlines out in 
the literal. The replace result above is exactly

"""\
lots of text hundreds of characters long\
more text on another line but we really don't want any line breaks\
in our final string\
so we replace newlines in this multiline string\
with an empty string thus\
"""

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list