Building a multiline string

Ulrich Eckhardt eckhardt at satorlaser.com
Thu Feb 4 07:09:46 EST 2010


Just for the record: Neither of the below methods actually produce a
multiline string. They only spread a string containing one line over
multiple lines of source code.

lallous wrote:
> Maybe that's already documented, but it seems the parser accepts to
> build a long string w/o really using the first method:
> 
> # Method1
> x = "line1" + \ # cannot use comments!
> "line2"+ \
> "line3"

Well, obviously you can't use comments like that there. The point of the
backslash is that it continues the current logical line over the
_immediately_ _following_ newline. If anything follows, that obviously
doesn't work.

> and instead using a list with one element like this:
> 
> # Method2
> x = [
> "line1" # can use comments
> "line2"
> "line3"
> ][0]

This basically makes use of the fact that "this" "is" "one" "string" and not
four strings.

> # Method3
> x = (
> "line1" # can use comments
> "line2"
> "line3"
> )

This uses the same, only that this time it uses brackets which cause an
expression to extend to multiple lines.

> (Not that I don't want new lines in the strings)

You don't not want or you don't want newlines? Depending on that, you could
also do this:

# method 4
x = "line1"\
    "line2"\
    "line3"

or maybe

# method 5
x = """line1
line2
line3
"""


> Now should I be using method 2 or 3 in production code?

I'd go for 3 or 4. 2 is basically a hack (you could do the same with a
dictionary, or a tuple, not only a list). 1 will actually create strings
and then concatenate them (unless Python is smart enough to optimize that),
but it allows adding expressions in the middle.

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list