Python:用一个空格替换双空格并删除单个空格

时间:2019-03-07 13:24:53

标签: python string

我想更改这样的字符串:

T h i s  i s  a  t e s t

收件人:

This is a test

这是我的代码,有效

    while '  ' in s:
      s = s.replace('  ', '$$')        
    while ' ' in s:
      s = s.replace(' ', '')
    while '$$' in s:
      s = s.replace('$$', ' ')     

但是,对此有简单的解决方案吗?

对于删除所有空格或删除单个空格并保留多个空格,也有类似的解决方案,但是在我的情况下,我也必须用单个空格替换双空格。

4 个答案:

答案 0 :(得分:3)

A little amendment to this and poof!

import re

s = 'T h i s  i s  a  t e s t'
print(re.sub(r'([^ ]) ([^ ])',r'\1 \2',s))

输出

This is a test

答案 1 :(得分:3)

s="T h i s  i s  a  t e s t"

s=" ".join([str(i).replace(" ","") for i in s.split("  ")])

这应该有效。

说明:

  1. 遇到两个空格时,通过分割字符串来创建新列表。
  2. 通过遍历先前构造的列表并替换每个项目中的空格来创建新列表。
  3. 通过加入先前创建的列表来创建新字符串,每个列表之间用空格分隔。

答案 2 :(得分:2)

您可以在re中使用否定的超前查询:

import re

s = 'T h i s  a  t e s t'
t = re.sub(r' (?! )', '', s)
print(t)

给予预期

This is a test

实际上,它会为每个空格序列删除一个空格:

>>> t= 'T h i s  i s   a    t e s t'
>>> re.sub(r' (?! )', '', t)
'This is  a   test'

答案 3 :(得分:0)

s = 'T h i s   i s   a   t e s t'
''.join([row[0] for row in zip(s, range(len(s)+1)) if row[1]%2==0])

结果:

'This is a test'
相关问题