How to write very long string that conforms with PEP8 and prevent E501
When handling long strings, Python allows you to split them into short segments enclosed in parentheses to implicitly join them — This way, it's both readable and PEP8 compliant:
You can also employ backslashes for explicit line continuation, but implicit joining tends to be cleaner:
Hold that thought, there're more strategies to deal with long strings while adhering to PEP8!
String Concatenation: The No '+' Rule
It's recommended not to use the +
operator for joining string literals in Python as it often results in less readable code:
The parenthesized strings, right besides each other, get concatenated implicitly and render line continuation superfluous.
Formatting With Spaces and Commas
If you have strings that need to be separated by commas and spaces, leave a comma and a blank space at the end of each line. This simple trick drastically improves the readability and editability:
Parentheses: Boon and Bane
When using parentheses, avoid unwanted tuples. It's important to be vigilant:
Forgive my Length, E501
Occasionally, you might need to bypass PEP8 with a long line that serves a specific purpose. In these cases, you can disable E501 using # noqa: E501
:
This is your "get out of jail free card" to avoid the error Code Police.
Using Fancy f-Strings
With f-strings, you can dynamically insert variables inside your long strings, all the while maintaining readability and complying with PEP8:
Tipping The Scales: Readability vs Compliance
There are times when preserving readability might warrant breaching the 79-character rule as prescribed by PEP8. Certain information, like URLs or error messages, are more understandable when kept whole. Breathe easy, for autoscaling formatters like Black, take care of these cases.
Was this article helpful?