How can I do a line break (line continuation) in Python?

后端 未结 11 1603
囚心锁ツ
囚心锁ツ 2020-11-21 22:56

I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?

For example, adding a bunch of strings,



        
11条回答
  •  灰色年华
    2020-11-21 23:29

    If you want to break your line because of a long literal string, you can break that string into pieces:

    long_string = "a very long string"
    print("a very long string")
    

    will be replaced by

    long_string = (
      "a "
      "very "
      "long "
      "string"
    )
    print(
      "a "
      "very "
      "long "
      "string"
    )
    

    Output for both print statements:

    a very long string

    Notice the parenthesis in the affectation.

    Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

    s = (
      '''2+2='''
      f"{2+2}"
    )
    

提交回复
热议问题