在字符串Python中查找并替换多个逗号/空格实例

在字符串Python中查找并替换多个逗号/空格实例,python,regex,string,python-3.x,text,Python,Regex,String,Python 3.x,Text,我有一个字符串,其中包含逗号+空格的多个连续实例,我想用一个实例替换它。有没有一个干净的方法可以做到这一点?我想正则表达式可能会有所帮助 一个天真的例子: s = 'a, b, , c, , , d, , , e, , , , , , , f 所需输出: 'a, b, c, d, e, f 当然,文本可以更改,因此搜索应该是连续的,。因此正则表达式搜索逗号+空格的两个或多个实例,然后在子函数中仅用一个替换它 没有注释中所建议的@Casimir et Hippolyte正则表达式 test_s

我有一个字符串,其中包含逗号+空格的多个连续实例,我想用一个实例替换它。有没有一个干净的方法可以做到这一点?我想正则表达式可能会有所帮助

一个天真的例子:

s = 'a, b, , c, , , d, , , e, , , , , , , f
所需输出:

'a, b, c, d, e, f

当然,文本可以更改,因此搜索应该是连续的,。

因此正则表达式搜索逗号+空格的两个或多个实例,然后在子函数中仅用一个替换它

没有注释中所建议的@Casimir et Hippolyte正则表达式

test_string = 'a, b, , c, , , d, , , e, , , , , , , f'
test_string_parts = test_string.split(',')
test_string_parts = [part.strip() for part in test_string_parts if part != ' ']
print ', '.join(test_string_parts)
>>> a, b, c, d, e, f
您可以使用reduce:


其中,x表示进位,y表示项目

解决问题的最简单方法是:

>>> s = 'a, b, , c, , , d, , , e, , , , , , , f'
>>> s = [x for x in s if x.isalpha()]
>>> print(s)
['a', 'b', 'c', 'd', 'e', 'f']
然后,使用join

>>> ', '.join(s)
'a, b, c, d, e, f'
一行完成:

>>> s = ', '.join([x for x in s if x.isalpha()])
>>> s
'a, b, c, d, e, f'
换个角度想想:

>>> s = 'a, b, , c, , , d, , , e, , , , , , , f'
>>> s = s.split()  #split all ' '(<- space)
>>> s
['a,', 'b,', ',', 'c,', ',', ',', 'd,', ',', ',', 'e,', ',', ',', ',', ',', ',', ',', 'f']
>>> while ',' in s:
...     s.remove(',')
>>> s
['a,', 'b,', 'c,', 'd,', 'e,', 'f']
>>> ''.join(s)
'a,b,c,d,e,f'

还有一个解决方案:检查列表和同一列表的组合,换言之,按连续项对移位,并从前一项与下一项不同的每对中选择第二项:

s = 'a. b. . c. . . d. . . e. . . . . . . f'
test = []
for i in s:
    if i != ' ':
        test.append(i)


res = [test[0]] + [y for x,y in zip(test, test[1:]) if x!=y]

for x in res:
    print(x, end='')
 
屈服

a.b.c.d.e.f
[Program finished]

谢谢这不是同样的工作方式吗:re.subr',\s{2,}',',,test_string?或者,是否有一些显著的区别或极端情况?它也会起作用。有关此处编译的更多信息:如果不是“,”我有“\n”,我将如何调整此查找和替换\\n{2,}似乎在中工作,但在Python中不工作。有什么建议吗?为什么不仅仅是r'\n{2,}'尝试了r'\n{2,}'。它无法在Python中捕获“\n”,在Python中如何获得如此均匀的位移?我不确定我是否理解这个问题。这是另一个简单的例子:然而。。。这只适用于单字母变量。。。请阅读这个问题:只需添加一个新方法。这个答案来自低质量的帖子。添加一些解释,即使代码是自解释的
s = ", , a, b, , c, , , d, , , e, , , ,  , , , f,,,,"
s = [o for o in s.replace(' ', '').split(',') if len(o)]
print (s)
s = 'a. b. . c. . . d. . . e. . . . . . . f'
test = []
for i in s:
    if i != ' ':
        test.append(i)


res = [test[0]] + [y for x,y in zip(test, test[1:]) if x!=y]

for x in res:
    print(x, end='')
 
a.b.c.d.e.f
[Program finished]