Search code examples
pythonsyntaxline-breakslong-lines

How can I do a line break (line continuation) in Python (split up a long line of source code)?


Given:

e = 'a' + 'b' + 'c' + 'd'

How do I write the above in two lines?

e = 'a' + 'b' +
    'c' + 'd'

See also: How do I split the definition of a long string over multiple lines? if there is a long string literal in the code that needs to be broken up to wrap the line nicely.


Solution

  • What is the line? You can just have arguments on the next line without any problems:

    a = dostuff(blahblah1, blahblah2, blahblah3, blahblah4, blahblah5, 
                blahblah6, blahblah7)
    

    Otherwise you can do something like this:

    if (a == True and
        b == False):
    

    or with explicit line break:

    if a == True and \
       b == False:
    

    Check the style guide for more information.

    Using parentheses, your example can be written over multiple lines:

    a = ('1' + '2' + '3' +
        '4' + '5')
    

    The same effect can be obtained using explicit line break:

    a = '1' + '2' + '3' + \
        '4' + '5'
    

    Note that the style guide says that using the implicit continuation with parentheses is preferred, but in this particular case just adding parentheses around your expression is probably the wrong way to go.