I’ve come across some code that looks something like this:
foo = r"""
Hello
How are you
Goodbye
"""
Is this convention just an easy way to keep the formatting of the string that could cause problems if it was made in the normal way? I’ve tried searching online but the nature of the problem doesn’t lend itself well to search terms.
It’s a triple-quoted python string literal. You can use
'''as well. (Therin front signals the literal is a raw string; e.g. most escape sequences are ignored; this applies to both single and triple-quoted strings).These strings preserve newlines, unlike single-quoted strings, where you’d have to use the
\nnewline escape code instead:The format has a miriad of uses. If I need to define a multi-line constant, I often use a backslash after the opening triple-quote to end up with a very readable string literal:
The most common usage however, is as a docstring; the first string literal of a function, class or module automatically is assigned to that object’s
__doc__attribute, for easy retrieval later by other tools (such as pydoc and doctests, especially if you follow the docstring conventions. By convention these usually are defined using tripple-quoted literals, even if there is only one line of documentation.