[Python-ideas] triple-quoted strings and indendation

Matthias Lehmann mat at matlehmann.de
Fri May 13 23:00:35 CEST 2011


Am 13.05.2011 19:17, schrieb Bruce Leban:
> If this feature were to be added, we would surely want to ignore the
> indentation on the first line regardless of the previous line since it
> shouldn't depend on whether or not I use two or four space indents:
>
>      fun_func(-"""
>          multiple
>          lines
> """)
> #   ^^^^ don't want these spaces in my string
>
> but unless we force people to follow the convention that you must have a
> line break after the opening """ we would need to ignore indentation
> starting with the second line for people who use this style:
>
>      fun_func(-"""foo
>                   bar
>                   more""")
>
> Now personally, I'd probably follow that first style but if this were a
> language feature I wouldn't think it should only work for one style.
> Here's pseudo-code:
>
>     if s[0] == '\n':  # style = first case above
>          strip first character and strip indentation starting with first
>     line
>     else if s[0] == ' ':
>          strip indentation starting with first line   # style = """\
>     else:
>          strip indentation starting with second line  # style = second
>     case above
>

The prototyped code for trimming of triple-quoted string as I proposed were:

def trim(start_column, lines):
         """ start_column: start-column of first line of the
                           triple-quoted string
             lines: the lines of the string
         """
         n = start_column
	for line in lines[1:]:
             m = get_index_of_first_non_whitespace_char(line)
             n = min(n, m)
         result = []
         if len(lines[0]) > 0:
             result.append(lines[1])
         for line in lines[1:]:
             result.append(line[n:])
         if len(lines[-1]) == 0:
             result = result[:-1]
         return '\n'.join(result)

The crux is to have the start_column available to the function, 
everything else could be done just with a function.

With this, following indendation styles are possible:

func(t"""foo
   bar
   more""")

func(t"""foo
          bar
          more""")

func(t"""
   foo
   bar
   more
   """)

All this would be possible with a function, too. The start_column is 
really only needed to support cases like this:

func(t"""   keep
               white
                  space
       """)




More information about the Python-ideas mailing list