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,616
  • 5
  • 25
  • 44
  • 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
  • 56,204
  • 11
  • 116
  • 135