Indented multi-line strings

Terry Reedy tjreedy at udel.edu
Thu May 31 13:12:22 EDT 2018


On 5/31/2018 10:39 AM, 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.

string = (
     "     Hello, this is a concatenated   \n"
     "   multiline variably indented       \n"
     "string with variable trailing blanks.\n"
     "    It works now and always has!     ")

-- 
Terry Jan Reedy




More information about the Python-list mailing list