Long lines
Dealing with long lines
PEP 8 requires lines that do not exceed 80 characters. Sometimes, in production-grade code we exceed this, but when we do so, we do so with good reason. You should get in the habit of working within this constraint, as long lines become hard to read. Here are some things you can do if you have long lines.
Implicit concatenation
Strings can be broken up quite nicely using implicit concatenation. Here’s how implicit concatenation works:
>>> "Implicit " "concatenation"
'Implicit concatenation'
Look at that. Python concatenated them without the “+” operator. We can use this to deal with long strings.
print("Here I'm using implicit concatenation to deal with "
"what otherwise might be an annoyingly long line "
"which if all on one line would certainly exceed "
"eighty characters, but here it does not. Yipee!")
This works with f-strings too. You only need to prefix the strings that have replacement fields.
= "Egbert Porcupine"
name = "Erethizon dorsatum"
species = 1960
birth_year = "Porcupine Mountains Wilderness State Park"
home = 2025
current_year
print(f"{{name}} was born in {birth_year} which makes him "
f"{current_year - birth_year} years old. This is "
"an unusual age for a member of the species "
f"{{species}} and it's quite likely that {{name}} is "
"the world's oldest living porcupine. He hails "
f"from {{home}}, one of the lovliest, and most "
"unspoiled wildernesses in North America.")
Implicit line continuation by wrapping in parentheses
When we have a long expression we can wrap the entire thing in parentheses.
= 3
x # Wrap a long expression in parentheses!
= (3 * x ** 14 + 4 * x ** 13 - 17 * x ** 12
y + 5 * x ** 11 - 22 * x ** 10 + 9 ** x * 9
- 42 * x ** 8 + 2 * x ** 7 - 401 * x ** 6
+ 2 * x ** 5 + 3 * x ** 4 - 15 * x ** 3
- 10 * x ** 2 + 6 * x - 7)
print(y)
The line continuation character
Python does have a line continuation character, the backslash (\
). Using the backslash to explicitly continue a line is discouraged and use of implicit line continuation (within parentheses, for example) is much preferred.
Here’s one example of a case where \
makes sense, just to satisfy your curiosity:
assert some_long_variable_name > another_long_variable_name \
and some_function(x, y) != 42, \
"Computation failed: result was 42 and value of \
another_long_variable_name is too small"
(You won’t see many examples in this book, though it is used here and there in code snippets in order to fit code within the width of the page and where using other approaches might be confusing).
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.