开发者

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()])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜