assigning multi-line strings to variables

Ben Finney ben+python at benfinney.id.au
Wed Apr 28 19:52:18 EDT 2010


Lie Ryan <lie.1296 at gmail.com> writes:

> Python have triple-quoted string when you want to include large amount
> of text; there is no need to split the string up manually or even
> scriptically.

You can even have multi-line string literals that have correct
indentation in the code, but strip that indentation at runtime::

    import textwrap

    def foo():
        """ Gyre and gimble in the wabe. """
        whiffle(textwrap.dedent("""\
                Jabberwocky

            ’Twas brillig, and the slithy toves
            Did gyre and gimble in the wabe;
            All mimsy were the borogoves,
            And the mome raths outgrabe.

            “Beware the Jabberwock, my son!
            The jaws that bite, the claws that catch!
            Beware the Jubjub bird, and shun
            The frumious Bandersnatch!”

            He took his vorpal sword in hand:
            Long time the manxome foe he sought—
            So rested he by the Tumtum tree,
            And stood awhile in thought.

            And as in uffish thought he stood,
            The Jabberwock, with eyes of flame,
            Came whiffling through the tulgey wood,
            And burbled as it came!

            One, two! One, two! and through and through
            The vorpal blade went snicker-snack!
            He left it dead, and with its head
            He went galumphing back.

            “And hast thou slain the Jabberwock?
            Come to my arms, my beamish boy!
            O frabjous day! Callooh! Callay!”
            He chortled in his joy.

            ’Twas brillig, and the slithy toves
            Did gyre and gimble in the wabe;
            All mimsy were the borogoves,
            And the mome raths outgrabe.

                    —Lewis Carroll
            """))

    def whiffle(text):
        """ Show the lines that have leading indentation. """
        for line in text.split("\n"):
            if line.startswith((" ", "\t")):
                print(line)

    foo()

The multi-line string is indented nicely within the code. When I run
this, I get::

        Jabberwocky
            —Lewis Carroll

showing that the only lines still indented are those that we *want* to
be indented within the string.

-- 
 \       “If consumers even know there's a DRM, what it is, and how it |
  `\     works, we've already failed.” —Peter Lee, Disney corporation, |
_o__)                                                             2005 |
Ben Finney



More information about the Python-list mailing list