[ACCEPTED]-Compress whitespaces in string-regex
Accepted answer
' '.join("some user entered text".split())
0
>>> import re
>>> re.sub("\s+"," ","some user entered text")
'some user entered text'
>>>
EDIT:
This will also replace line breaks 2 and tabs etc.
If you specifically want spaces 1 / tabs you could use
>>> import re
>>> re.sub("[ \t]+"," ","some user entered text")
'some user entered text'
>>>
>>> re.sub(r'\s+', ' ', 'ala ma\n\nkota')
'ala ma kota'
0
You can use something like this:
text = 'sample base text with multiple spaces'
' '.join(x for x in text.split() if x)
OR:
text = 'sample base text with multiple spaces'
text = text.strip()
while ' ' in text:
text = text.replace(' ', ' ')
0
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.