Spezial whitespace strip...

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Benutzeravatar
jens
Python-Forum Veteran
Beiträge: 8502
Registriert: Dienstag 10. August 2004, 09:40
Wohnort: duisburg
Kontaktdaten:

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()

GitHub | Open HUB | Xing | Linked in
Bitcoins to: 1JEgSQepxGjdprNedC9tXQWLpS424AL8cd
Antworten