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:
("This is the first line of my text, "
"which will be joined to a second.")
Or with line ending continuations, which is a little more fragile, as this works:
"This is the first line of my text, " \
"which will be joined to a second."
But this doesn't:
"This is the first line of my text, " \
"which will be joined to a second."
See the difference? No? Well you won't when it's your code either.
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 (+
):
("This is the first line of my text, " +
"which will be joined to a second.")
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 the first line of my text
which will be joined to a second."""
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 is the first line of my text \
which will be joined to a second."""
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.