查找和替换字符串中的多个逗号/空格实例,Python

Ole*_*kov 4 python regex string text python-3.x

我有一个字符串,其中包含多个连续的,(逗号+空格)实例,我想用一个实例替换它。有没有干净的方法来做到这一点?我想 RegEx 会有所帮助。

一个天真的例子:

s = 'a, b, , c, , , d, , , e, , , , , , , f
Run Code Online (Sandbox Code Playgroud)

所需的输出:

'a, b, c, d, e, f
Run Code Online (Sandbox Code Playgroud)

自然,文本可以更改,因此应该搜索 的连续实例,

Duš*_*ďar 6

因此,正则表达式搜索(逗号 + 空格)的两个或多个实例,,然后在sub函数中只用一个,.

import re
pattern = re.compile(r'(,\s){2,}')

test_string = 'a, b, , c, , , d, , , e, , , , , , , f'
print re.sub(pattern, ', ', test_string)
>>> a, b, c, d, e, f
Run Code Online (Sandbox Code Playgroud)

并且没有正则表达式(如@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
Run Code Online (Sandbox Code Playgroud)