Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap long lines in Python [duplicate]

Tags:

python

string

People also ask

How do you wrap a long line in Python?

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.

What if a line is too long in Python?

If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.

How do you break a long condition in Python?

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

How do you duplicate a line in Python?

Alternatively, you can press Ctrl+Shift+A , start typing the command name in the popup, and then choose it there. The duplicated line or multi-line selection is inserted below the original line or selection; the duplicated inline selection is inserted to the right of the original.


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.


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))

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)