Thomas Guest: Aligning the first line of a triple-quoted string in Python

Python’s triple-quoted strings are a convenient syntax for strings where the contents span multiple lines. Unescaped newlines are allowed in triple-quoted strings. So, rather than write:

song = ("Happy birthday to you\n"         "Happy birthday to you\n"         "Happy birthday dear Gail\n"         "Happy birthday to you\n") 

you can write:

song = """Happy birthday to you Happy birthday to you Happy birthday dear Gail Happy birthday to you """ 

The only downside here is that the first line doesn’t align nicely with the lines which follow. The way around this is to embed a \newline escape sequence, meaning both backslash and newline are ignored.

song = """\ Happy birthday to you Happy birthday to you Happy birthday dear Gail Happy birthday to you """ 

Planet Python

Leave a Reply

Your email address will not be published. Required fields are marked *