The Python Oracle

Python style - line continuation with strings?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5 Looping

--

Chapters
00:00 Python Style - Line Continuation With Strings?
01:28 Accepted Answer Score 283
01:43 Answer 2 Score 54
02:08 Answer 3 Score 4
02:25 Answer 4 Score 6
02:32 Thank you

--

Full question
https://stackoverflow.com/questions/5437...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #codingstyle

#avk47



ACCEPTED ANSWER

Score 283


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!")



ANSWER 2

Score 54


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"



ANSWER 3

Score 6


This is a pretty clean way to do it:

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



ANSWER 4

Score 4


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)))