我有一个字符串,其中包含,
(逗号+空格)的多个连续实例,我想用单个实例替换它们。有干净的方法吗?我认为RegEx可以提供帮助。
一个天真的例子:
s = 'a, b, , c, , , d, , , e, , , , , , , f
所需的输出:
'a, b, c, d, e, f
当然,文本可以更改,因此搜索应该是{em>连续 ,
的实例。
答案 0 :(得分:4)
因此,正则表达式搜索两个或更多 ,
(逗号+空格)实例,然后在sub
函数中只用一个{{1}替换它}}
,
且没有正则表达式(在评论中建议 @Casimir et Hippolyte )
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
答案 1 :(得分:2)
您可以使用reduce
:
>>> from functools import reduce
>>> reduce( (lambda x, y: x+', '+y if y else x), s.split(', '))
(其中x是进位,y是项目)
答案 2 :(得分:1)
解决问题的最简单方法是:
>>> 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'
答案 3 :(得分:1)
s = ", , a, b, , c, , , d, , , e, , , , , , , f,,,,"
s = [o for o in s.replace(' ', '').split(',') if len(o)]
print (s)
答案 4 :(得分:0)
另一种解决方案:遍历列表和相同列表的组合,移动一个(换句话说,通过连续项目对),然后从第一(前一个)项目不同于的每一对中选择第二个项目第二个(下一个)项目:
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]