Building a multiline string

Marco Mariani marco at sferacarta.com
Thu Feb 4 08:23:46 EST 2010


On 02/04/2010 12:34 PM, lallous wrote:

> Now should I be using method 2 or 3 in production code?

Another way... depending on what you are using the string for, of
course. If it's an HTML/XML/SQL/whatever piece of code:

>>>> from textwrap import dedent
>>>> sql = dedent("""
> ...              SELECT *
> ...                FROM table
> ...               WHERE foo=bar
> ...              """)
>>>> 
>>>> print sql
> 
> SELECT *
>   FROM table
>  WHERE foo=bar
> 


And if you don't want the starting/ending newlines:

>>>> sql = dedent("""\
> ...              SELECT *
> ...                FROM table
> ...               WHERE foo=bar\
> ...              """)
>>>> 
>>>> print sql
> SELECT *
>   FROM table
>  WHERE foo=bar             
>>>> 

I use this sometimes to keep both python and the embedded code readable
while preserving indentation.





More information about the Python-list mailing list