python 删除字符串中的连续空格只保留一个
PHPz
PHPz 2017-04-17 11:12:27
0
3
966

python 中如何删除字符串连续的空格,只保留一个呢?

PHPz
PHPz

学习是最好的投资!

reply all(3)
PHPzhong

Is this okay?

s = "abc  def   ghi       xy"
print ' '.join(filter(lambda x: x, s.split(' ')))
@felix021 in the comment, yes, there is no need to filter out the '' empty string, just connect it directly:
 ' '.join(s.split())
大家讲道理

Use regular expressions:

import re
re.sub(r'\s+', ' ', 'dfadf   dfa  ds ')
Peter_Zhu

Last regular rule (it is said that this is considered an abuse of regular rules)

import re
re.sub(' +', ' ', s)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template