At some point, you will want to define a multi-line string and find that the obvious solutions just don’t feel clean. In this post, I’m going to take a look at three ways of defining them and give you my recommendation.
Concatenation
The first way of doing it, and the way that immediately comes to mind, is to just add the strings to each other, like so:
1
2
3
|
template = “This is the first line.\n” + \
“This is the second line.\n” + \
“This is the third line.”
|
In my opinion, this looks extremely ugly. You can make it a bit better by omitting the + signs. This also works:
1
2
3
|
template = “This is the first line.\n” \
“This is the second line.\n” \
“This is the third line.”
|
That’s better, but still a bit of an eyesore. Let’s move on.
Multi-line string syntax
Another way is to use the built-in multi-line string syntax, like so:
1
2
3
|
template = “””This is the first line.
This is the second line.
This is the third line.”””
|
That’s much better than concatenation, but it has one conspicuous wart. You can’t indent the subsequent lines to be at the same level of indentation as the first one. The space will be interpreted as part of the string. The first line will be flush with the margin and the subsequent lines will be indented.
1
2
3
4
5
6
7
|
>>> template = “””This is the first line.
This is the second line.
This is the third line.”””
>>> print(template)
This is the first line.
This is the second line.
This is the third line.
|
Tuple syntax
There is another way to do it that doesn’t suffer from the ugliness of concatenation or the indentation wart of the multi-line syntax, and that is to use the tuple syntax.
I have no idea why this works, but it does:
1
2
3
|
template = (“This is the first line.\n”
“This is the second line.\n”
“This is the third line.”)
|
Note that you have to add the line breaks into the strings, because they’re not put in automatically. Nonetheless, I think this is by far the nicest, most readable method.