假设我的字符串是
a = ' Hello, I am trying to strip spaces perfectly '
Run Code Online (Sandbox Code Playgroud)
我知道:
a.strip()将删除前导和前导空格.a.replace(" ","")我可以删除一个空格等如何表达这一点,以便无论有多少空格,输出总是会被渲染为每个单词之间只有一个空格而在开头或结尾都没有?
(在python和Unix中)...谢谢!
您可以使用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)
| 归档时间: |
|
| 查看次数: |
175 次 |
| 最近记录: |