search

Home  >  Q&A  >  body text

python 删除字符串中的连续空格只保留一个

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

PHPzPHPz2783 days ago929

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-17 11:14:27

    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())

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 11:14:27

    Use regular expressions:

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

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 11:14:27

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

    import re
    re.sub(' +', ' ', s)

    reply
    0
  • Cancelreply