Skip to main content
 首页 » 编程设计

python之从python中的字符串中删除连续的重复字符

2025年05月04日21yxwkf

嘿,我正在尝试编写一个程序,该程序将从字符串中删除连续的重复字符。

例如:
字符串->aabbccde
第一次迭代:bbccde
第二次迭代:ccde
第三次迭代:de

de 是答案。

下面是我写的程序。

a = "aabbcs" 
def remove_dups(st,ind): 
    print st, ind 
    st = st.replace(st[ind], "") 
    print st, "in dups" 
    find_dups(st) 
 
def find_dups(text): 
    s=text 
    print s, "in find" 
    ln = len(s) 
    print ln 
    fg = 0 
    ind = 0 
    if ln==1: 
        print s, 'len' 
        return s 
    for i in range(0,ln-1): 
        if(s[i]==s[i+1]): 
            ind = i 
            remove_dups(s,ind) 
    print s, 'check'         
    return s 
 
ans = find_dups(a) 
print 'answer', ans 

下面是我得到的输出

找到aabbcs
6
aabbcs 0
英国广播公司的骗局
英国广播公司在寻找
4
英国广播公司 0
补刀
cs 在查找中
2
CS检查
英国广播公司检查
aabbcs 2
aacs 重复
找到 aacs
4
0
补刀
cs 在查找中
2
CS检查
aacs 检查
aabbcs 检查
回答 aabbcs

在上面我们得到了 cs 但答案仍然是原始字符串,我可以理解这是因为递归,但无法理解如何解决这个问题。一点帮助将不胜感激。谢谢!

请您参考如下方法:

python 有一些更简单的方法来做到这一点,其中之一:

>>> dup_string = 'aabcbccde' 
>>> from itertools import groupby 
>>> ''.join([x for x,y in groupby(dup_string) if sum(1 for i in y)<2]) 
'bcbde' 
>>> dup_string = 'aabbccde' 
>>> ''.join([x for x,y in groupby(dup_string) if sum(1 for i in y)<2]) 
'de' 
>>>