How to write very long string that conforms with PEP8 and prevent E501 How to write very long string that conforms with PEP8 and prevent E501 python python

How to write very long string that conforms with PEP8 and prevent E501


Also, because neighboring string constants are automatically concatenated, you can code it like this too:

s = ("this is my really, really, really, really, really, really, "       "really long string that I'd like to shorten.")

Note no plus sign, and I added the extra comma and space that follows the formatting of your example.

Personally I don't like the backslashes, and I recall reading somewhere that its use is actually deprecated in favor of this form which is more explicit. Remember "Explicit is better than implicit."

I consider the backslash to be less clear and less useful because this is actually escaping the newline character. It's not possible to put a line end comment after it if one should be necessary. It is possible to do this with concatenated string constants:

s = ("this is my really, really, really, really, really, really, " # comments ok     "really long string that I'd like to shorten.")

I used a Google search of "python line length" which returns the PEP8 link as the first result, but also links to another good StackOverflow post on this topic: "Why should Python PEP-8 specify a maximum line length of 79 characters?"

Another good search phrase would be "python line continuation".


Implicit concatenation might be the cleanest solution:

s = "this is my really, really, really, really, really, really," \    " really long string that I'd like to shorten."

Edit On reflection I agree that Todd's suggestion to use brackets rather than line continuation is better for all the reasons he gives. The only hesitation I have is that it's relatively easy to confuse bracketed strings with tuples.


I think the most important word in your question was "suggests".

Coding standards are funny things. Often the guidance they provide has a really good basis when it was written (e.g. most terminals being unable to show > 80 characters on a line), but over time they become functionally obsolete, but still rigidly adhered to. I guess what you need to do here is weigh up the relative merits of "breaking" that particular suggestion against the readability and mainatinability of your code.

Sorry this doesn't directly answer your question.