Wrap long lines in Python
def fun():
print(('{0} Here is a really long '
'sentence with {1}').format(3, 5))
Adjacent string literals are concatenated at compile time, just as in C. http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation is a good place to start for more info.
You could use the following code where indentation doesn't matter:
>>> def fun():
return ('{0} Here is a really long'
' sentence with {1}').format(3, 5)
You just need to enclose string in the parentheses.
You can use the fact that Python concatenates string literals which appear adjacent to each other:
>>> def fun():
... print '{0} Here is a really long ' \
... 'sentence with {1}'.format(3, 5)
Using concatenation of adjacent string literals, together with formatted string literals is the way to go:
x = 2
sep = 2 * '\n'
print(
'This message is so long that it requires '
f'more than {x} lines.{sep}'
'And more lines may be needed.')
This approach complies with PEP 8 and allows better use of space.
No +
operators needed, no backslashes for line continuation, no irregularities of indentation, no error-prone +=
to an accumulator string variable (which can be mistyped as =
, resulting in a silent error), no stray parenthesis hanging below the print
(the arguments are placed in their own level of indentation, and the next element at the indentation level of print
is the next statement).
Starting the strings on the line below the line that contains the print(
reduces indentation, and is more readable. Readability stems from both print(
standing out, by being on its own line, and by the uniform alignment of consecutive statements of this form.
The reduction in indentation from this approach becomes more evident when raising exceptions:
raise ModuleNotFoundError(
'aaaaaaaaaaaaaaaaaaaaaaaa'
'aaaaaaaaaaaaaaaaaaaaaaaa'
f'aaaaa {x} aaaaa')
Regarding formatted string literals (signified by the prefix "f", as in f'...'
), raw strings can be formatted string literals, by combining the prefixes "r" and "f":
rf'This is a formatted raw string, {sep}here is a backslash \.'
Note that raw strings are necessary for including literal backslashes without writing \\
. Otherwise, in a future CPython version, a SyntaxError
will be raised. As of Python 3.9, a DeprecationWarning
is raised:
python -X dev -c '"\q"'
outputs:
<string>:1: DeprecationWarning: invalid escape sequence \q
The replacements are very readable. In particular, this approach makes writing code that generates code or mathematical formulas a very pleasant task.
Rarely, the method str.format
may be suitable, due to what substitutions are needed. It can be used as follows:
print((
'This message is so long that it requires '
'more than {x} lines.{sep}'
'And more lines may be needed.'
).format(x=x, sep=sep))