Hello all,
I’m looking to find out what is the proper, pythonic way of printing multi-line strings, for example a message for a programs user.
The issue I’ve come across concerns indentation; when print() is nested inside a statement such as an if-then or try-except, the call to print() will be indented. If one wishes to continue the printed string onto subsequent lines in the .py file, all lines after the first must be aligned with the left margin (i.e not indented) as any indentation will be printed to the user. Consider the following example…
if True:
print('The Owl and the Pussy-Cat went to sea in a beautiful pea green boat\n\
they took some honey and plenty of money wrapped up in a five pound note')
The result would be a second line that was indented by four places past the first line within the output of the program. Docstrings exhibit the same behaviour…
if True:
print('''The Owl and the Pussy-Cat went to sea in a beautiful pea green boat\n
they took some honey and plenty of money wrapped up in a five pound note''')
The only solutions I’ve come up with so far are either to not indent any of the lines after the first…
if True:
print('The Owl and the Pussy-Cat went to sea in a beautiful pea green boat\n\
they took some honey and plenty of money wrapped up in a five pound note')
Or to replace all instances of four consecutive white-space characters with an empty string…
if True:
print('The owl and the Pussy-Cat went to sea in a beautiful pea green boat\n\
they took some honey and plenty of money wrapped up in a five pound note'.replace(' ', ''))
In BASH there is a notation that can be used to write here-documents containing tabs that the shell will ignore…
if true; then
cat <<- _EOF_
The Owl and the Pussy-Cat went to sea in a beautiful pea green boat
they took some honey and plenty of money wrapped up in a five pound note
_EOF_
fi
I’m pretty much looking for something like the above, but if there is a more proper or ‘pythonic’ way to do it then please let me know!