[Python-ideas] New str whitespace cleaning method?

Ron Adam ron3200 at gmail.com
Tue May 21 16:13:42 CEST 2013



On 05/21/2013 07:07 AM, Joao S. O. Bueno wrote:
> What about an STR method for just formatting whitespace?
>
> I propose starting with something that would just replace all occurrences of
> white-space sequences with a single white-space, and another mode that
> does the same, but preserves newlines.
>
> That way multiline strings could be used in a straight way to enter
> any desired construct.
>
> I know of textwrap.dedent - but it is not quite the same behavior, and this is a
> case wher having method call postfixed to the string has clear advantages
> over a function call with the same string - since the function name
> would have to be placed between the "strign destiantion" - which
> denotes its purpose, and the string text itself:


> Ex.:
>
> log.warn(dedent("""Hello dear sir,
>                                I am sorry to inform you
>                                the spanish inquisition
>                                has arrived"""))
>
> Against:
> log.warn("""Hello dear sir,
>                    I am sorry to inform you
>                    the spanish inquisition
>                    has arrived""".lint())

If the text can be reformatted then use the fill function from the textwrap 
module.

     result = fill(text, width=40)    # whitespace cleanup + wrap text.

Just make the width longer than the string to not wrap it.


I prefer to assign the text to a name first.

message = \
     """
     Hello dear sir,
     I am sorry to inform you
     the spanish inquisition
     has arrived
     """
log.warn(fill(message, width=40))


-Ron




More information about the Python-ideas mailing list