[Python-ideas] Multi-line strings that respect indentation

Ben Finney ben+python at benfinney.id.au
Fri Nov 5 02:18:51 CET 2010


Daniel da Silva <ddasilva at umd.edu> writes:

> On several occasions I have run into code that will do something like the
> following with a multiline string:
>
> def some_func():
> >     x, y = process_something()
> >
> >     val = """
> > <xml>
> >   <myThing>
> >     <val>%s</val>
> >     <otherVal>%s</otherVal>
> >   </myThing>
> >
> </xml>
> > """ % (x, y)
> >
> >     return val
> >
>
> To me, this is rather ugly because it messes up the indentation of
> some_func(). Suppose we could have a multiline string, that when
> started on a line indented four spaces, ignores the first four spaces
> on each line of the literal when creating the actual string?

The standard library time machine to the rescue::

    import textwrap

    def some_func():
        x, y = process_something()
    
        val = textwrap.dedent("""
            <xml>
              <myThing>
                <val>%s</val>
                <otherVal>%s</otherVal>
              </myThing>
            
            </xml>
            """) % (x, y)

        return val

I use this technique very often in my code. I'm surprised that it
doesn't have a wider share of Python programmers. Spread the knowledge!

-- 
 \      “I don't want to live peacefully with difficult realities, and |
  `\     I see no virtue in savoring excuses for avoiding a search for |
_o__)                        real answers.” —Paul Z. Myers, 2009-09-12 |
Ben Finney




More information about the Python-ideas mailing list