0

Assume my string is

a = '    Hello, I  am     trying  to       strip spaces  perfectly '

I know that:

  • Stripping using a.strip() will remove preceding and leading spaces.
  • Using a.replace(" ","") I can remove one space etc

How to formulate this so that no matter how many spaces there are the output will always be rendered as only one space between each word and none at the start or end?

(in python and Unix) ... thanks!

L P
  • 1,776
  • 5
  • 25
  • 46
  • Obviously, the Python part has a duplicate. However, the unix part is off-topic, and belongs on unix.stackexchange.com or superuser.com. – Ben Collins Jul 31 '13 at 11:47

1 Answers1

7

You can use str.split() then str.join(). Using str.split will automatically get rid of extra whitespace:

>>> a = '    Hello, I  am     trying  to       strip spaces  perfectly '
>>> print ' '.join(a.split())
Hello, I am trying to strip spaces perfectly

Using shell tools (thank you AdamKG!) :

$ echo '    Hello, I  am\n     trying  to       strip spaces  perfectly ' | tr -s "[:space:]" " " | sed -e 's/^ *//' -e 's/ *$//'
Hello, I am trying to strip spaces perfectly
Community
  • 1
  • 1
TerryA
  • 58,805
  • 11
  • 114
  • 143
  • This is a particularly nice way to do it, because it handles all white space including tabs and newlines, not just spaces. – Codie CodeMonkey Jul 23 '13 at 10:57
  • Thanks! Waiting on the UNIX solution to this – L P Jul 23 '13 at 10:58
  • `echo ' Hello, I am trying to strip spaces perfectly ' | tr -s "[:space:]" " " | sed -e 's/^ *//' -e 's/ *$//'` output: `Hello, I am trying to strip spaces perfectly` – AdamKG Jul 23 '13 at 11:03
  • well dammit, ate my extra spaces. Will edit the answer and include in a block. – AdamKG Jul 23 '13 at 11:04
  • Could you please explain the second pipe Adam? thanks – L P Jul 23 '13 at 11:06
  • @AdamKG Hey adam, I much appreciate the edit. Thank you very much :) – TerryA Jul 23 '13 at 11:07
  • 1
    @LP the tr step just collapses sequences of whitespace into a single space, the 2nd pipe (sed) strips the leftover leading/trailing space. – AdamKG Jul 23 '13 at 11:14
  • 1
    You can use `sed` for all the processing if you are going to use it at all. `sed 's/ */ /g;s/^ //;s/ $//' <<<' Hello, I am trying to strip spaces perfectly ' ` – tripleee Jul 23 '13 at 11:16
  • Nice! And TIL about ';' to chain sed commands, I've been using multiple -e args. – AdamKG Jul 23 '13 at 11:32