如何在Python和UNIX中删除空格,以便在整个字符串中均匀地呈现一个空格

L P*_*L P 0 python unix

假设我的字符串是

a = '    Hello, I  am     trying  to       strip spaces  perfectly '
Run Code Online (Sandbox Code Playgroud)

我知道:

  • 剥离使用a.strip()将删除前导和前导空格.
  • 使用a.replace(" ","")我可以删除一个空格等

如何表达这一点,以便无论有多少空格,输出总是会被渲染为每个单词之间只有一个空格而在开头或结尾都没有?

(在python和Unix中)...谢谢!

Ter*_*ryA 7

您可以使用str.split()然后str.join().使用str.split将自动摆脱额外的空白:

>>> a = '    Hello, I  am     trying  to       strip spaces  perfectly '
>>> print ' '.join(a.split())
Hello, I am trying to strip spaces perfectly
Run Code Online (Sandbox Code Playgroud)

使用shell工具(谢谢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
Run Code Online (Sandbox Code Playgroud)