[Python-ideas] New str whitespace cleaning method?
Wolfgang Maier
wolfgang.maier at biologie.uni-freiburg.de
Fri May 24 19:52:39 CEST 2013
Wolfgang Maier <wolfgang.maier at ...> writes:
>
> Joao S. O. Bueno <jsbueno <at> ...> writes:
>
> >
> > 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())
> >
>
> Haven't really thought that through, but couldn't you write a decorator that
> does the dedenting, and that you then use on your warn()?
> This way, you wouldn't have to care about the formatting at all in your
> actual code.
> Best,
> Wolfgang
>
ok, here's example code for it:
from textwrap import dedent
class dedentify(object):
def __init__ (self, f):
self.f = f
def __call__ (self, message):
self.f(dedent(message))
@dedentify
def warn (message):
print (message)
warn("""\
Hello dear sir,
I am sorry to inform you
the spanish inquisition
has arrived""")
now prints:
Hello dear sir,
I am sorry to inform you
the spanish inquisition
has arrived
I hope this is what you had in mind ?
Wolfgang
More information about the Python-ideas
mailing list