string substitutions

John Machin sjmachin at lexicon.net
Sun Feb 24 01:02:05 EST 2002


Mike Dean <klaatu at evertek.net> wrote in message news:<mailman.1014496298.16453.python-list at python.org>...
> * Bob Roberts <bobnotbob at byu.edu> [2002-23-02 11:52]:
> > What would be a good way to replace every one or more spaces (" ") in
> > a string with just one space?  Or replace any number of newlines with
> > just one?
> 
> This is a perfect job for Python's regular expression (RE) library. For
> example:
> 
> import re
> 
> # Replace all occurances of one or more spaces with a single space
> re.sub(' +', ' ', mystring)

Not using raw strings with re? Not a good habit ...

> # Ditto for newlines
> re.sub('\n+', '\n', mystring)
> # And, to combine the two into one operation:
> re.sub('(\n+| +)', '\1', mystring)

and *whammo* here's the result.

>>> mystring = "aaaa\n\n\n\nbbbbbbb\n\n\nbb\nbbbb"
>>> re.sub('(\n+| +)', '\1', mystring)
'aaaa\x01bbbbbbb\x01bb\x01bbbb'
>>>



More information about the Python-list mailing list