removing random whitespace
All,
I have some indexed text that I would like to format in a more uniform manor. For ex开发者_开发问答ample:
I live in Virginia and it is raining today
I would like that to print out as
I live in Virginia and it is raining today
I am writing my application in Python so if anyone knows how to do this sort of string manipulation, it would be greatly appreciated.
Adam
A very simple approach:
s = "I live in Virginia and it is raining today"
words = s.split()
print ' '.join(words)
You could use a regular expression to accomplish this
import re
s = 'I live in Virginia and it is raining today'
print re.sub(r'\s+', ' ', s)
Regular expressions do work here, but are probably overkill. One line without any imports would take care of it:
sentence = 'I live in Virginia and it is raining today'
' '.join([segment for segment in sentence.split()])
精彩评论