How would you go about formatting a long line such as this? I’d like to get it to no more than 80 characters wide:
logger.info("Skipping {0} because its thumbnail was already in our system as {1}.".format(line[indexes['url']], video.title))
Is this my best option?
url = "Skipping {0} because its thumbnail was already in our system as {1}."
logger.info(url.format(line[indexes['url']], video.title))
That’s a start. It’s not a bad practice to define your longer strings outside of the code that uses them. It’s a way to separate data and behavior. Your first option is to join string literals together implicitly by making them adjacent to one another:
Or with line ending continuations, which is a little more fragile, as this works:
But this doesn’t:
See the difference? No? Well you won’t when it’s your code either.
(There’s a space after
\in the second example.)The downside to implicit joining is that it only works with string literals, not with strings taken from
variables, so things can get a little more hairy when you refactor. Also, you can only interpolate formatting on the combined string as a whole.
Alternatively, you can join explicitly using the concatenation operator (
+):Explicit is better than implicit, as the zen of python says, but this creates three strings instead of one, and uses twice as much memory: there are the two you have written, plus one which is the two of them joined together, so you have to know when to ignore the zen. The upside is you can apply formatting to
any of the substrings separately on each line, or to the whole lot from outside the parentheses.
Finally, you can use triple-quoted strings:
This is often my favorite, though its behavior is slightly different as the newline and any leading whitespace on subsequent lines will show up in your final string. You can eliminate the newline with an escaping backslash.
This has the same problem as the same technique above, in that correct code only differs from incorrect code by invisible whitespace.
Which one is "best" depends on your particular situation, but the answer is not simply aesthetic, but one of subtly different behaviors.