1

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.

1
  • 2
    Strings enclosed by triples quotation marks can span multiple lines. New lines within the string are preserved. Commented Aug 11, 2012 at 10:20

2 Answers 2

4

It's a triple-quoted python string literal. You can use ''' as well. (The r in 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 \n newline escape code instead:

>>> """Line one
... Line two"""
'Line one\nLine two'

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:

LOREM_IPSUM = """\
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
"""

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.

Sign up to request clarification or add additional context in comments.

1 Comment

plus, in the OP's example it's a raw string, i.e. escape sequences disabled: When an 'r' or 'R' prefix is present, a character following a backslash is included in the string without change, and all backslashes are left in the string.
0

What is the "normal way"? Triple quotes are useful when you want your string to span multiple lines. The formal documentation is here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.