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.

Answer from Harley Holcombe on Stack Overflow
Top answer
1 of 11
1591

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.

2 of 11
322

From PEP 8 -- Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

Backslashes may still be appropriate at times. For example, long, multiple with-statements cannot use implicit continuation, so backslashes are acceptable:

with open('/path/to/some/file/you/want/to/read') as file_1, \
     open('/path/to/some/file/being/written', 'w') as file_2:
    file_2.write(file_1.read())

Another such case is with assert statements.

Make sure to indent the continued line appropriately.

The preferred place to break around a binary operator is after the operator, not before it. Some examples:

class Rectangle(Blob):

  def __init__(self, width, height,
                color='black', emphasis=None, highlight=0):
       if (width == 0 and height == 0 and
          color == 'red' and emphasis == 'strong' or
           highlight > 100):
           raise ValueError("sorry, you lose")
       if width == 0 and height == 0 and (color == 'red' or
                                          emphasis is None):
           raise ValueError("I don't think so -- values are %s, %s" %
                            (width, height))
       Blob.__init__(self, width, height,
                     color, emphasis, highlight)file_2.write(file_1.read())

Update

PEP8 now recommends the opposite convention (for breaking at binary operations) used by mathematicians and their publishers to improve readability.

Donald Knuth's style of breaking before a binary operator aligns operators vertically, thus reducing the eye's workload when determining which items are added and subtracted.

From PEP8: Should a line break before or after a binary operator?:

Donald Knuth explains the traditional rule in his Computers and Typesetting series: "Although formulas within a paragraph always break after binary operations and relations, displayed formulas always break before binary operations"[3].

Following the tradition from mathematics usually results in more readable code:

# Yes: easy to match operators with operands
income = (gross_wages
          + taxable_interest
          + (dividends - qualified_dividends)
          - ira_deduction
          - student_loan_interest)

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style is suggested.

[3]: Donald Knuth's The TeXBook, pages 195 and 196

๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ breaking-long-lines-code-python
Breaking up long lines of code in Python - Python Morsels
May 6, 2021 - We could break this line into two by putting a backslash (\) at the end of the line and then pressing the Enter key: from collections.abc import Hashable, Iterable, KeysView, Mapping, \ MutableMapping, Set ยท This is a way of telling Python ...
Discussions

Is it possible to break a long line to multiple lines in Python? - Stack Overflow
Just like C, you can break a long line into multiple short lines. But in Python, if I do this, there will be an indent error... Is it possible? More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to break line lines of code into multiple lines?
The PEP-8 section , for reference. I would chop up the long string like so: big_string = ("PROJCS['NAD_1983_StatePlane_Georgia_West_FIPS_1002_Feet'," "GEOGCS['GCS_North_American_1983'," "DATUM['D_North_American_1983'," "SPHEROID['GRS_1980',6378137.0,298.257222101]]," "PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]]," "PROJECTION['Transverse_Mercator']," "PARAMETER['False_Easting',2296583.333333333]," "PARAMETER['False_Northing',0.0]," "PARAMETER['Central_Meridian',-84.16666666666667]," "PARAMETER['Scale_Factor',0.9999]," "PARAMETER['Latitude_Of_Origin',30.0]," "UNIT['Foot_US',0.3048006096012192]]") arcpy.DefineProjection_management(photoKeyFC, big_string) More on reddit.com
๐ŸŒ r/learnpython
8
3
December 20, 2018
formatting - How can I break up this long line in Python? - Stack Overflow
How can I do a line break (line continuation) in Python (split up a long line of source code)? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Wrapping long lines by using Python's implied line continuation - Grist Creators
Hello, just ran into another unexpected issue: trying to wrap (break) a long line of code (a long formula) into multiple lines Here is the code that works: AND(NOT(ISERROR($Notification_DueDt.strftime("%y-%m-%d"))), $Done_Result=="", ISERROR($Completed.strftime("%y-%m-%d"))) Here is what I ... More on community.getgrist.com
๐ŸŒ community.getgrist.com
0
January 13, 2022
๐ŸŒ
Note.nkmk.me
note.nkmk.me โ€บ home โ€บ python
Write a Long String on Multiple Lines in Python | note.nkmk.me
May 19, 2025 - Python allows implicit line continuation within parentheses (), brackets [], or braces {} โ€” meaning you can break a line without needing a backslash. Since [] and {} are used for lists and sets, respectively, parentheses () are typically used ...
๐ŸŒ
Doingmathwithpython
doingmathwithpython.github.io โ€บ breaking-long-lines-in-python.html
Breaking long lines in Python
November 4, 2015 - The line continuation operator, \ can be used to split long statements over multiple lines. Here is how we could split the above statement using \ instead: s3 = x + x**2/2 + x**3/3 \ + x**4/4 + x**5/5 \ + x**6/6 + x**7/7 \ + x**8/8 ยท At the end of every line (except the last), we just add ...
Top answer
1 of 7
787

From PEP 8 - Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately.

Example of implicit line continuation:

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


b = some_function(
    param1=foo(
        "a", "b", "c"
    ),
    param2=bar("d"),
)

On the topic of line breaks around a binary operator, it goes on to say:

For decades the recommended style was to break after binary operators. But this can hurt readability in two ways: the operators tend to get scattered across different columns on the screen, and each operator is moved away from its operand and onto the previous line.

In Python code, it is permissible to break before or after a binary operator, as long as the convention is consistent locally. For new code Knuth's style (line breaks before the operator) is suggested.

Example of explicit line continuation:

a = '1'   \
    + '2' \
    + '3' \
    - '4'
2 of 7
256

There is more than one way to do it.

1). A long statement:

>>> def print_something():
         print 'This is a really long line,', \
               'but we can make it across multiple lines.'

2). Using parenthesis:

>>> def print_something():
        print ('Wow, this also works?',
               'I never knew!')

3). Using \ again:

>>> x = 10
>>> if x == 10 or x > 0 or \
       x < 100:
       print 'True'

Quoting PEP8:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. If necessary, you can add an extra pair of parentheses around an expression, but sometimes using a backslash looks better. Make sure to indent the continued line appropriately. The preferred place to break around a binary operator is after the operator, not before it.

๐ŸŒ
DataCamp
datacamp.com โ€บ tutorial โ€บ how-to-line-break-in-python
A Comprehensive Guide on How to Line Break in Python | DataCamp
May 17, 2024 - Explicit line continuation involves using the backslash (\) character at the end of a line to show that the statement extends to the next line. Hereโ€™s an example of a Python line break in a string: long_string = "This is a very long string that \ spans multiple lines for readability."
Find elsewhere
๐ŸŒ
Codingem
codingem.com โ€บ home โ€บ how to break long lines in python
How to Break Long Lines in Python - codingem.com
October 15, 2022 - To avoid too long chains of comparisons, you can break the line. ... if (is_rainy == True and is_hot == True and is_sunny == True and is_night == True): print("How is that possible...?") Pythonโ€™s implicit continuation makes it possible to break long expressions into multi-line expressions.
๐ŸŒ
Better Stack
betterstack.com โ€บ community โ€บ questions โ€บ python-how-to-define-multiline-string
How do I split the definition of a long string over multiple lines in Python? | Better Stack Community
To split a long string over multiple lines in Python, you can use the line continuation character, which is a backslash (\) at the end of the line.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ how to break line lines of code into multiple lines?
r/learnpython on Reddit: How to break line lines of code into multiple lines?
December 20, 2018 -

Hello! I'm a novice when it comes to working with python, so I apologize for the extremely basic question. The IDE I am using (pyCharm) is giving me a PEP 8 error (line too long). For a lot of the code I am working on. I understand that this isn't a hard constraint of python. Just something to improve readability, which I would like to do. Currently I have a line (below) that shoots way off the screen, and it is just annoying to make changes to it. I can't figure out how to spread the line of code across multiple lines while still getting python to parse it correctly. I hope this make sense. Can anyone provide any pointers? Thanks for your help!

The current monstrosity:



    arcpy.DefineProjection_management(photoKeyFC, "PROJCS['NAD_1983_StatePlane_Georgia_West_FIPS_1002_Feet',GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',2296583.333333333],PARAMETER['False_Northing',0.0],PARAMETER['Central_Meridian',-84.16666666666667],PARAMETER['Scale_Factor',0.9999],PARAMETER['Latitude_Of_Origin',30.0],UNIT['Foot_US',0.3048006096012192]]")
    

    More or less what I'd like to see:
    
    "PROJCS['NAD_1983_StatePlane_Georgia_West_FIPS_1002_Feet',GEOGCS['GCS_North_American_1983',DATUM['D_North_
American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.017453292
5199433]],PROJECTION['Transverse_Mercator'],PARAMETER['False_Easting',2296583.333333333],PARAMETER['False_Northi

ng',0.0],PARAMETER['Central_Meridian',-84.16666666666667],PARAMETER['Scale_Factor',0.9999],PARAMETER['Latitude_Of _Origin',30.0],UNIT['Foot_US',0.3048006096012192]]")

๐ŸŒ
InterviewQs
interviewqs.com โ€บ ddi-code-snippets โ€บ break-long-line-python
Break a long line into multiple lines in Python - InterviewQs
Using ( )The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.
๐ŸŒ
YouTube
youtube.com โ€บ python morsels
Breaking up long lines of code in Python - YouTube
Have a long line of Python code? If you don't have brackets or braces on your line yet, you can add parentheses wherever you'd like and put line breaks withi...
Published ย  June 29, 2022
Views ย  2K
Top answer
1 of 6
458

That's a start. It's not a bad practice to define your longer strings outside of the code that uses them. It's a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:

("This is the first line of my text, "
"which will be joined to a second.")

Or with line ending continuations, which is a little more fragile, as this works:

"This is the first line of my text, " \
"which will be joined to a second."

But this doesn't:

"This is the first line of my text, " \ 
"which will be joined to a second."

See the difference? No? Well you won't when it's your code either.

(There's a space after \ in the second example.)

The downside to implicit joining is that it only works with string literals, not with strings taken from variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.

Alternatively, you can join explicitly using the concatenation operator (+):

("This is the first line of my text, " + 
"which will be joined to a second.")

Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to any of the substrings separately on each line, or to the whole lot from outside the parentheses.

Finally, you can use triple-quoted strings:

"""This is the first line of my text
which will be joined to a second."""

This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.

"""This is the first line of my text \
which will be joined to a second."""

This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.

Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.

2 of 6
62

Consecutive string literals are joined by the compiler, and parenthesized expressions are considered to be a single line of code:

logger.info("Skipping {0} because it's thumbnail was "
  "already in our system as {1}.".format(line[indexes['url']],
  video.title))
๐ŸŒ
Kite
kite.com โ€บ python โ€บ answers โ€บ how-to-break-a-long-line-of-code-in-python
Code Faster with Line-of-Code Completions, Cloudless Processing
Kite is a free autocomplete for Python developers. Code faster with the Kite plugin for your code editor, featuring Line-of-Code Completions and cloudless processing.
๐ŸŒ
James Madison University
w3.cs.jmu.edu โ€บ spragunr โ€บ CS240_F14 โ€บ style_guide.shtml
CS240 Python Coding Conventions
The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.
๐ŸŒ
Grist Creators
community.getgrist.com โ€บ t โ€บ wrapping-long-lines-by-using-pythons-implied-line-continuation โ€บ 503
Wrapping long lines by using Python's implied line continuation - Grist Creators
January 13, 2022 - Hello, just ran into another unexpected ... Here is the code that works: AND(NOT(ISERROR($Notification_DueDt.strftime("%y-%m-%d"))), $Done_Result=="", ISERROR($Completed.strftime("%y-%m-%d"))) Here is what I ......
๐ŸŒ
W3docs
w3docs.com โ€บ python
Is it possible to break a long line to multiple lines in Python?
Yes, it is possible to break a long line of code into multiple lines in Python. One way to do this is by using the line continuation character, which is a backslash (\).
๐ŸŒ
Intellipaat
intellipaat.com โ€บ home โ€บ blog โ€บ how to split a long string over multiple lines in python?
How to Split a Long String Over Multiple Lines in Python? - Intellipaat
February 2, 2026 - Explanation: This is an example of how to break a long string into several lines by using parentheses so that the string can be continued without the explicit use of line breaks. The join() function with List can be used to store the parts of the string and then join them together. ... Code Copied! ... Explanation: long_string = โ€ โ€œ.join([]), This command fetches and returns multiple lines of strings into a single line. Python uses f-string with parentheses to display multiple lines of string in one line.