As PEP8 suggests keeping below the 80 column rule for your python program, how can I abide to that with long strings, i.e.
s = "this is my really, really, really, really, really, really, really long string that I'd like to shorten."
How would I go about expanding this to the following line, i.e.
s = "this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten."
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.
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".
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.
You lost a space, and you probably need a line continuation character, ie. a \
.
s = "this is my really, really, really, really, really, really" + \
" really long string that I'd like to shorten."
or even:
s = "this is my really, really, really, really, really, really" \
" really long string that I'd like to shorten."
Parens would also work instead of the line continuation, but you risk someone thinking you intended to have a tuple and had just forgotten a comma. Take for instance:
s = ("this is my really, really, really, really, really, really"
" really long string that I'd like to shorten.")
versus:
s = ("this is my really, really, really, really, really, really",
" really long string that I'd like to shorten.")
With Python's dynamic typing, the code may run either way, but produce incorrect results with the one you didn't intend.
Backslash:
s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."
or wrap in parens:
s = ("this is my really, really, really, really, really, really" +
"really long string that I'd like to shorten.")
With a \
you can expand statements to multiple lines:
s = "this is my really, really, really, really, really, really" + \
"really long string that I'd like to shorten."
should work.
These are all great answers, but I couldn't find an editor plugin that would help me with editing "implicitly concatenated" strings, so I wrote a package to make it easier on me.
On pip (install paragraphs) if whoever's wandering this old thread would like to check it out. Formats multi-line strings the way html does (compress whitespace, two newlines for a new paragraph, no worries about spaces between lines).
from paragraphs import par
class SuddenDeathError(Exception):
def __init__(self, cause: str) -> None:
self.cause = cause
def __str__(self):
par(
f"""
Y - e - e - e - es, Lord love you! Why should she die of
influenza? She come through diphtheria right enough the year
before. I saw her with my own eyes. Fairly blue with it, she was.They
all thought she was dead; but my father he kept ladling gin down
her throat til she came to so sudden that she bit the bowl off the
spoon.
What call would a woman with that strength in her have to die of
influenze? What become of her new straw hat that should have
come to me? Somebody pinched it; and what I say is, them as pinched
it done her in."""
)
becomes ...
Y - e - e - e - es, Lord love you! Why should she die of influenza? She come through...
What call would a woman with that strength in her have to die of influenza? What...
Everything lines up easily with (Vim) 'gq'
Available options:
- backslash:
"foo" \ "bar"
- plus sign followed by backslash:
"foo" + \ "bar"
- brackets:
("foo" "bar")
- brackets with plus sign:
("foo" + "bar")
- PEP8, E502: the backslash is redundant between brackets
Avoid
Avoid brackets with comma: ("foo", "bar")
which defines a tuple.
>>> s = "a" \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = "a" + \
... "b"
>>> s
'ab'
>>> type(s)
<class 'str'>
>>> s = ("a"
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>> s = ("a",
... "b")
>>> type(s)
<class 'tuple'>
>>> s = ("a" +
... "b")
>>> type(s)
<class 'str'>
>>> print(s)
ab
>>>
I tend to use a couple of methods not mentioned here for specifying large strings, but these are for very specific scenarios. YMMV...
Multi-line blobs of text, often with formatted tokens (not quite what you were asking, but still useful):
error_message = ''' I generally like to see how my helpful, sometimes multi-line error messages will look against the left border. '''.strip()
Grow the variable piece-by-piece through whatever string interpolation method you prefer:
var = 'This is the start of a very,' var = f'{var} very long string which could' var = f'{var} contain a ridiculous number' var = f'{var} of words.'
Read it from a file. PEP-8 doesn't limit the length of strings in a file; just the lines of your code. :)
Use brute-force or your editor to split the string into managaeble lines using newlines, and then remove all newlines. (Similar to the first technique I listed):
foo = ''' agreatbigstringthatyoudonotwanttohaveanyne wlinesinbutforsomereasonyouneedtospecifyit verbatimintheactualcodejustlikethis '''.replace('\n', '')
I've used textwrap.dedent in the past. It's a little cumbersome so I prefer line continuations now but if you really want the block indent, I think this is great.
Example Code (where the trim is to get rid of the first '\n' with a slice):
import textwrap as tw
x = """
This is a yet another test.
This is only a test"""
print(tw.dedent(x[1:]))
Explanation:
From what I can tell, dedent calculates the indentation based on the white space in the first line of text before a new line. So I added a newline to make it easy to line up the code. To avoid the newline, you'd have to add to the first line of text extra white space so that subsequent lines would have their indentation reduced as you desire. If you wanted to tweak it, you could easily reimplement it using the re
module.
This method has limitations in that very long lines way still be longer than you want in which case other methods that concatenate strings is more suitable.
来源:https://stackoverflow.com/questions/1874592/how-to-write-very-long-string-that-conforms-with-pep8-and-prevent-e501