Spezial whitespace strip...
Verfasst: Mittwoch 3. Dezember 2008, 17:31
Mal wieder was zum optimieren, wer lust hat. Denn so richtig gut finde ich meine Lösung nicht:
Code: Alles auswählen
import re
space_re = re.compile(r"^(\s*)(.*?)(\s*)$", re.DOTALL)
def clean_whitespace(txt):
"""
>>> clean_whitespace(u"\\n\\nfoo bar\\n\\n")
u'\\nfoo bar\\n'
>>> clean_whitespace(u" foo bar \\n \\n")
u' foo bar\\n'
>>> clean_whitespace(u" \\n \\n foo bar ")
u'\\nfoo bar '
>>> clean_whitespace(u"foo bar")
u'foo bar'
"""
def striped(txt):
if "\n" in txt:
return "\n"
elif " " in txt:
return " "
else:
return ""
def cleanup(match):
#print "all:", repr(match.group(0))
start, txt, end = match.groups()
return striped(start) + txt + striped(end)
return space_re.sub(cleanup, txt)
if __name__ == '__main__':
import doctest
doctest.testmod()