[Tutor] How to normalize/compress whitespace in a string?

Kent Johnson kent37 at tds.net
Fri Apr 11 15:22:11 CEST 2008


Malcolm Greene wrote:
> Any suggestions for how to normalize and compress whitespace in a
> string?
> 
> By normalize I mean convert tabs and soft spaces (extended ascii code
> 160) to spaces.
> 
> By compress I mean replace all runs of 2 or more spaces (after the
> normalization step) to a single space.
> 
> I know I can use regular expressions to accomplish the above, but
> thought that might be too heavy handed.

I would say it is appropriate. string.translate() can do the 
normalization but I would still use a regex to compress so you might as 
well do it all in a single re.sub().

Kent


More information about the Tutor mailing list