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?
-
One can also break the call of methods (obj.method()) in multiple lines with parenthesis around, https://stackoverflow.com/a/64812795/687896 – Brandt Nov 12 '20 at 22:33
7 Answers
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 = some_function(
'1' + '2' + '3' - '4')
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'

- 30,738
- 21
- 105
- 131

- 1,023,142
- 271
- 3,287
- 2,928
-
38For the second example, it does not like spaces (which you cannot see) after the ' \' – cardamom Mar 09 '17 at 11:49
-
@cardamom This issue is not a particularity of python; for instance, if you try to write a shell script, e.g., a `for` loop for creating directories: `for i in dir1\ `(new line) `dir2\ ` (new line) `dir3\ ` (new line) `... mkdir $i` in order for this script to run, there must be no space after the backslash – DavidC. Aug 07 '17 at 17:26
-
1@cardamom Actually it does not like *any character* (except newlines). Too bad for comments… – Skippy le Grand Gourou Oct 30 '19 at 10:33
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.

- 25,046
- 18
- 72
- 90

- 126,773
- 69
- 172
- 181
-
This came up during a talk on code style at PyOhio and we came to the conclusion that 2) was a good standard way to go. It's not perfect since changing the text isn't as easy, but at least it reads ok. – Rick Nov 13 '10 at 16:53
-
@user225312 could you also use''' code newline more code'''' or this a bad habit? – onxx Apr 06 '15 at 22:14
-
-
first one gives me a SyntaxError in IDLE(v.3.5), why? Also, if I don't start with a parenthesis gives me same error with missing parenthesis. With parentheses gives me nothing – Yannis Dran Nov 22 '16 at 23:05
-
3Last sentence that mentions breaking _after_ the operator, is opposed to what [PEP8](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator) suggests of breaking _before_ the operator to improve readability. – milpita Jan 17 '17 at 19:02
-
I don't know if PEP8 was changed, but your quote does not exist, and states the exact opposite of what PEP8 says. For new code, PEP8 says to put the line break before the operator. – denshigomi Apr 18 '20 at 18:42
If you want to assign a long string to variable, you can do it as below:
net_weights_pathname = (
'/home/acgtyrant/BigDatas/'
'model_configs/lenet_iter_10000.caffemodel')
Do not add any comma, or you will get a tuple which contains many strings!

- 30,738
- 21
- 105
- 131

- 1,721
- 1
- 16
- 24
-
10This works because python automatically concatenates the strings inside the parenthesis, without the need of putting a `+` operator. – blueFast Oct 17 '17 at 14:30
-
For string interpolation, put `f` before each short string, ```uri = (f"example.com/version8.2/apps/{self.market}" f"/app/{self.product_name}/ranks?start_date={self.week_ago_str}&end_date={self.today_str}")``` – Charlie 木匠 Jul 23 '18 at 19:05
-
This also works well if you place all your strings in a multi-line string, i.e. between triple ", e.g. ( """line 1 line2""") , and possibly won't carry the "comma risk" :) – jmng Jul 25 '18 at 17:17
When trying to enter continuous text (say, a query) do not put commas at the end of the line or you will get a list of strings instead of one long string:
queryText= "SELECT * FROM TABLE1 AS T1"\
"JOIN TABLE2 AS T2 ON T1.SOMETHING = T2.SOMETHING"\
"JOIN TABLE3 AS T3 ON T3.SOMETHING = T2.SOMETHING"\
"WHERE SOMETHING BETWEEN <WHATEVER> AND <WHATEVER ELSE>"\
"ORDER BY WHATEVERS DESC"
kinda like that.
There is a comment like this from acgtyrant
, sorry, didn't see that. :/

- 189
- 1
- 4
-
1This won't work - you need some white-space at either the beginning or end of each quoted string. There will currently be no space between "T1" and "JOIN". In the example above, just use multi-line strings with `'''` or `"""`, SQL won't mind the CR/LF's. – dsz Jan 06 '20 at 23:16
DB related code looks easier on the eyes in multiple lines, enclosed by a pair of triple quotes:
SQL = """SELECT
id,
fld_1,
fld_2,
fld_3,
......
FROM some_tbl"""
than the following one giant long line:
SQL = "SELECT id, fld_1, fld_2, fld_3, .................................... FROM some_tbl"

- 639
- 7
- 10
-
2It is a just a workaround, but using docstrings as strings is not a pythonic way to code. – Mohammad ElNesr Jan 29 '18 at 09:07
-
8@Mohammad This is just a regular [triple-quoted string](https://docs.python.org/3/glossary.html#term-triple-quoted-string), not a [docstring](https://docs.python.org/3/glossary.html#term-docstring). – wjandrea Jun 01 '19 at 16:07
-
This will result in a new line break `\n` append into each line instead of line continuation. Like "'SELECT\nid,\nfld_1\nFROM some_tbl\n'" – liviaerxin Apr 26 '23 at 03:39
As far as I know, it can be done. Python has implicit line continuation (inside parentheses, brackets, and strings) for triple-quoted strings ("""like this"""
) and the indentation of continuation lines is not important. For more information, you may want to read this article on lexical analysis, from python.org.

- 30,738
- 21
- 105
- 131

- 39,737
- 6
- 87
- 123
-
3Strings only do implicit continuation inside triple-quoted strings. That's the distinction between triple- and single-quoted. – Ned Batchelder Nov 13 '10 at 12:34