string substitutions
Sheila King
usenet at thinkspot.net
Sat Feb 23 15:40:52 EST 2002
[posted and mailed]
On 23 Feb 2002 11:52:10 -0800, bobnotbob at byu.edu (Bob Roberts) wrote in
comp.lang.python in article
<c4e6b17d.0202231152.5f87765d at posting.google.com>:
> 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 function, which I'm currently using in an email filter, replaces
all '\n' characters with a space, and then replaces all occurrences of
more than one space with a single space.
def remove_new_lines(searchstring):
""" Returns a string without newlines or double spaces. """
newline = '\n'
# Replace newlines with spaces
newstring = searchstring.replace(newline, ' ')
# Replace multiple spaces with single spaces
while newstring.find(' ') > -1:
newstring = newstring.replace(' ', ' ')
return newstring
You could also do this with regular expressions, but this method only
requires regular string operations.
--
Sheila King
http://www.thinkspot.net/sheila/
"When introducing your puppy to an adult cat,
restrain the puppy, not the cat." -- Gwen Bailey,
_The Perfect Puppy: How to Raise a Well-behaved Dog_
More information about the Python-list
mailing list