Pythonic way to create a long multi-line string

后端 未结 27 1654
滥情空心
滥情空心 2020-11-22 00:47

I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a +<

27条回答
  •  [愿得一人]
    2020-11-22 00:55

    Are you talking about multi-line strings? Easy, use triple quotes to start and end them.

    s = """ this is a very
            long string if I had the
            energy to type more and more ..."""
    

    You can use single quotes too (3 of them of course at start and end) and treat the resulting string s just like any other string.

    NOTE: Just as with any string, anything between the starting and ending quotes becomes part of the string, so this example has a leading blank (as pointed out by @root45). This string will also contain both blanks and newlines.

    I.e.,:

    ' this is a very\n        long string if I had the\n        energy to type more and more ...'
    

    Finally, one can also construct long lines in Python like this:

     s = ("this is a very"
          "long string too"
          "for sure ..."
         )
    

    which will not include any extra blanks or newlines (this is a deliberate example showing what the effect of skipping blanks will result in):

    'this is a verylong string toofor sure ...'
    

    No commas required, simply place the strings to be joined together into a pair of parenthesis and be sure to account for any needed blanks and newlines.

提交回复
热议问题