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

Since neighboring string constants are automatically concatenated, you can code it like this:

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”.

Leave a Comment