[Python-ideas] Idea for new multi-line triple quote literal

Ron Adam ron3200 at gmail.com
Mon Jul 1 07:56:26 CEST 2013



On 06/30/2013 08:57 PM, Guido van Rossum wrote:
> On Sun, Jun 30, 2013 at 6:47 PM, Nick Coghlan<ncoghlan at gmail.com>  wrote:
>> >On 1 July 2013 11:09, Steven D'Aprano<steve at pearwood.info>  wrote:
>>> >>but in either case, I think the choice of --- as delimiter is ugly and
>>> >>arbitrary, and very likely is ambiguous (currently, x = ---1 is legal code).
>>> >>Similar suggestions to this have been made many times before, you should
>>> >>search the archives:
>>> >>
>>> >>http://mail.python.org/mailman/listinfo/python-ideas
>> >
>> >I'm still partial to the idea of offering textwrap.indent() and
>> >textwrap.dedent() as string methods.
>> >
>> >1. You could add a ".dedent()" at the end of a triple quoted string
>> >for this kind of problem. For a lot of code, the runtime cost isn't an
>> >issue.
>> >2. A JIT would definitely be able to avoid recalculating the result every time
>> >3. Even CPython may eventually gain constant folding for that kind of
>> >method applied directly to a string literal
>> >4. I dedent and indent long strings more often than I capitalize,
>> >center, tab expand, or perform various other operations which already
>> >grace the str type as methods.
> That's a compelling argument. Let's do it. (Assuming the definition of
> exactly how to indent or dedent is not up for discussion -- if there
> are good reasons to disagree with textwrap now's the time to bring it
> up.)

It would be an improvement to have them as methods, but I'd actually like 
to have Str.indent(n) method that takes a value for the leading white space.

The value to this method would always be a positive number, and any common 
leading white space would be replaced by the new indent amount.

S.indent(0) would be the same as S.dedent().

s = """\
A multi-line string
with 4 leading spaces.
""".indent(4)


      s = """\
          A multi-line string
          with 4 leading spaces.
	 """.indent(4)


      if cond:
          s = """\
              Another multi-line string
              with 4 leading spaces.
              """.indent(4)



The reason I prefer this is ...

It's more relevant to what I'm going to use the string for and is not just 
compensating for the block indention level, which has nothing to do with 
how I'm going to use the string.

It explicitly specifies the amount of leading white space I want in the 
resulting string object.  If I want a different indent level, I can just 
change the value.  Or call the indent method again with the new value.

I don't need to know what the current leading white space is on the string, 
just what I want for my output.



Strangely, the online docs for textwrap include an indent function that 
works a bit different, but it is no longer present in textwrap. Looks like 
an over site to me.

Cheers,
     Ron















More information about the Python-ideas mailing list