string substitutions

Mike C. Fletcher mcfletch at geocities.com
Sat Feb 23 16:20:54 EST 2002


Another approach to the original problem (replace X instances of Y with 
a single instance of Y)...:

 >>> import string
 >>> data = 'this\n\nthose\n\n\nthem\ntheir\nthose'
 >>> string.join(filter( None, string.split( data, '\n')), '\n')
'this\nthose\nthem\ntheir\nthose'
 >>>

Which has the virtue of letting you do the same thing with _any_ 
character or multi-character string just by parameterising '\n' in the 
above.

For your particular code (replace \n _and_ ' ' with single spaces), why not:

 >>> data = 'this\n\nthose\n\n  \nt s a s t o v hem\ntheir\nthose'
 >>> string.join(string.split(data ), ' ')
'this those t s a s t o v hem their those'

Which replaces all whitespace runs with the single space...

Enjoy,
Mike


Sheila King wrote:
> [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.
> 
> 


-- 
_______________________________________
   Mike C. Fletcher
   http://members.rogers.com/mcfletch/






More information about the Python-list mailing list