Since I couldnt retain the format which I wanted in the mail, I am rewording my question.
Hi all,
I am having adjacent multiple white spaces(both leading, trailing and in the middle) in a string. I want to strip off all the multiple white spaces and need to substitute multiple whitespaces by one white space there. Is there any way for that.?
I know that leading and trailing whitespaces can be stripped by rstrip and lstrip. But I couldnt do anythign with multiple whitespaces in the middle of a string
Can anybody help me out please?
~Sas
1) you can strip off trailing and leading whitespaces using strip(). So there's no need for lstrip,rstrip
eg
-
>>> s = " a string with leading and trailing spaces "
-
>>> s.strip()
-
'a string with leading and trailing spaces'
-
2) if you know the number of multiple white spaces in the middle, eg 2 white spaces, you can use replace() , eg for 2 white spaces
-
>>> s = "a string with multiple white spaces"
-
>>> s.replace(" "," ")
-
'a string with multiple white spaces'
-
>>>
-
3) if you don't know the number of white spaces in the middle, you can use split(), which i think is most straight forward :)
-
>>> s = "a string with multiple white spaces"
-
>>> s.split()
-
['a', 'string', 'with', 'multiple', 'white', 'spaces']
-
>>> ' '.join(s.split())
-
'a string with multiple white spaces'
-
4) you can also use regular expression module eg
-
>>> import re
-
>>> s = "a string with multiple white spaces"
-
>>> re.sub("\s+" , " ", s)
-
'a string with multiple white spaces'
-