1

All,

I have some indexed text that I would like to format in a more uniform manor. For example:

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

aeupinhere
  • 2,883
  • 6
  • 31
  • 39
  • Regexes to trim spaces between words to just 1 in this: possible duplicate of [Trim whitespace from middle of string](http://stackoverflow.com/questions/216870/trim-whitespace-from-middle-of-string). If you don't know Python's `re` module, this is an answer that shows it's use: http://stackoverflow.com/questions/216870/trim-whitespace-from-middle-of-string/1250923#1250923 – wkl Sep 07 '11 at 17:45
  • `re.sub(r'[ \t]{2,}', ' ', str)`. Be careful when using `\s` instead, since that includes new lines and carriage returns. – NullUserException Sep 07 '11 at 17:47

3 Answers3

9

A very simple approach:

s = "I    live in  Virginia   and it is  raining     today"
words = s.split()
print ' '.join(words)
Jochen Ritzel
  • 104,512
  • 31
  • 200
  • 194
3

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)
ScArcher2
  • 85,501
  • 44
  • 121
  • 160
  • As NullUserException pointed out - r'[ \t]{2,}' would be used to replace spaces or tabs. I just did a general whitespace replace in my answer. – ScArcher2 Sep 07 '11 at 17:54
0

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()])
Jordan Reiter
  • 20,467
  • 11
  • 95
  • 161
Jordan Bouvier
  • 308
  • 2
  • 7