Python style - line continuation with strings? [duplicate]

In trying to obey the python style rules, I've set my editors to a max of 79 cols.

In the PEP, it recommends using python's implied continuation within brackets, parentheses and braces. However, when dealing with strings when I hit the col limit, it gets a little weird.

For instance, trying to use a multiline

mystr = """Why, hello there
wonderful stackoverflow people!"""

Will return

"Why, hello there\nwonderful stackoverflow people!"

This works:

mystr = "Why, hello there \
wonderful stackoverflow people!"

Since it returns this:

"Why, hello there wonderful stackoverflow people!"

But, when the statement is indented a few blocks in, this looks weird:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
wonderful stackoverflow people!"

If you try and indent the second line:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there \
            wonderful stackoverflow people!"

Your string ends up as:

"Why, hello there                wonderful stackoverflow people!"

The only way I've found to get around this is:

do stuff:
    and more stuff:
        and even some more stuff:
            mystr = "Why, hello there" \
            "wonderful stackoverflow people!"

Which I like better, but is also somewhat uneasy on the eyes, as it looks like there is a string just sitting in the middle of nowhere. This will produce the proper:

"Why, hello there wonderful stackoverflow people!"

So, my question is - what are some people's recommendations on how to do this and is there something I'm missing in the style guide that does show how I should be doing this?

Thanks.


Solution 1:

Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:

print("Why, hello there wonderful "
      "stackoverflow people!")

Solution 2:

Just pointing out that it is use of parentheses that invokes auto-concatenation. That's fine if you happen to already be using them in the statement. Otherwise, I would just use '\' rather than inserting parentheses (which is what most IDEs do for you automatically). The indent should align the string continuation so it is PEP8 compliant. E.g.:

my_string = "The quick brown dog " \
            "jumped over the lazy fox"

Solution 3:

Another possibility is to use the textwrap module. This also avoids the problem of "string just sitting in the middle of nowhere" as mentioned in the question.

import textwrap
mystr = """\
        Why, hello there
        wonderful stackoverfow people"""
print (textwrap.fill(textwrap.dedent(mystr)))

Solution 4:

This is a pretty clean way to do it:

myStr = ("firstPartOfMyString"+
         "secondPartOfMyString"+
         "thirdPartOfMyString")