Sunday 4 December 2011

How to strip of mulitiple white spaces.

During this post, I want to share some different solutions for stripping multiple white spaces in the  sentence.
We need to strip the multiple spaces betweens the words. look the following solution. 

Example:
>>> str='Multiple      white  spaces'
>>> for i in str.split():
...     print i,
... 
Multiple white spaces
you can strip off trailing and leading whitespaces using strip(). So there's no need for lstrip,rstrip
Example:
>>> str='    multiple white     spaces    '
>>> str.strip()
'multiple white     spaces'

If you know the number of multiple white spaces in the middle, example, 2 white spaces, you can use replace() , example for 2 white spaces:
Example:
>>> str='How  to strip    multiple  white  spaces'
>>> str.replace("  "," ")
'How to strip  multiple white spaces'
Example for stripping multiple white spaces :
>>> str='How  to strip    multiple  white  spaces'
>>> ' '.join(str.split())
'How to strip multiple white spaces'

No comments:

Post a Comment