Indented multi-line strings

MRAB python at mrabarnett.plus.com
Thu May 31 11:44:10 EDT 2018


On 2018-05-31 15:39, Dan Strohl via Python-list wrote:
>> This is of course not a problem if the *trailing* quote determines the
>> indentation:
>> 
>>     a_multi_line_string = i'''
>>            Py-
>>           thon
>>         '''
> 
> I get the point, but it feels like it would be a pain to use, and it "Feels" different from the other python indenting, which is something that I would want to stay away from changing.
> 
>> > In any case, Chris made a good point that I agree with. This doesn't
>> > really need to be syntax at all, but could just be implemented as a
>> > new string method.
>> 
>> Depending on the details, not quite. A method wouldn't get the horizontal
>> position of the leading quote. It could infer the position of the trailing quote,
>> though.
>> 
> 
> What about if we used Chris's approach, but added a parameter to the method to handle the indent?
> 
> For example,
> 
> Test = """
>          Hello, this is a
>       Multiline indented
>      String
>      """.outdent(4)
> 
> 
> The outdent method could look like:
> 
> string.outdent(size=None)
>      """
>      :param size : The number of spaces to remove from the beginning of each line in the string.  Non space characters will not be removed.  IF this is None, the number of characters in the first line of the string will be used.  If this is an iterable, the numbers returned from each iteration will be used for their respective lines.  If there are more lines than iterations, the last iteration will be used for subsequent lines.
> 
> This solves the problem in a very pythonic way, while allowing the flexibility to handle different needs.
> 
That string starts with a blank line, after the initial quotes.

I was also thinking that it could take the indentation from the first 
line, but that if you wanted the first line to have a larger indent than 
the remaining lines, you could replace the first space that you want to 
keep with a non-whitespace character and then pass that character to the 
method.

For example:

Test = """\
      _   Hello, this is a
       Multiline indented
      String
      """.outdent(padding='_')

Outdent so that the first line is flush to the margin:

_   Hello, this is a
  Multiline indented
String

The padding argument tells it to replace the initial '_':

     Hello, this is a
  Multiline indented
String



More information about the Python-list mailing list