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

MRAB python at mrabarnett.plus.com
Sat Nov 6 19:35:07 CET 2010

On 05/11/2010 20:43, Jared Grubb wrote:
> I like the idea of have d""" as the marker, as I've often wanted this
> for writing out custom HTML or source code.
> But, would the level of dedent be based on the level of indent of the
> code line containing the d""" marker? If so, would you want a
> parsing/syntax error if the string violated the indentation levels of
> the surrounding code? (the dedent would have to take place
> post-parsing, since the grammar knows nothing about INDENT tokens
> inside strings, so it's not truly a "parser" error).
> The easiest would be to do the equivalent of dedent and take the
> longest common whitespace length. But, the purist in me would kinda
> hope that if, for example, the code was indented to column 8 but the
> text was all at column 12, that the resulting string would have 4
> leading spaces on each line.
You could also add an 'indent' method to strings:

text.indent(4) would indent each line by 4 spaces

text.indent(-4) would dedent each line by 4 spaces; an exception would
be raised if a line started with fewer than 4 spaces, unless that line
contained only spaces.

text.indent(4, '>') would indent each line by 4 * '>'.

More information about the Python-ideas mailing list