查找字符串中的连续字母

时间:2019-04-29 23:50:45

标签: python string

我想找到连续的字符数,并用字母#count打印为> 3,否则打印所有字母 我想得到:B#6CCCBBB

但是我得到B#5CCCBBB作为输出。我缺少第0个元素。

str1 = "BBBBBBCCCBBB"
def consecutive_alpha(str1):   
count = 0
new_string = ""
n = 3
for i in range(0, len(str1)-1):
    if str1[i] == str1[i+1]:
        count += 1
        if i == (len(str1)-2):
            if count > n:                
                new_string = new_string + str1[i] +"#" + str(count)
            else:
                new_string = new_string + str1[i]*count
    else:
        if count > n:                
            new_string = new_string + str1[i] +"#" + str(count)
        else:
            new_string = new_string + str1[i]*count
        count = 1            
print new_string


consecutive_alpha(str1)

3 个答案:

答案 0 :(得分:2)

为什么不只使用$ tree . . ├── A │   ├── A to Z │   ├── Ace inc │   ├── Apples │   │   ├── file1 │   │   └── file2.3 │   └── Austerity ├── B │   ├── Beeline Industries │   ├── Bing │   └── Booze inc. ├── C │   ├── Cans │   │   ├── file1 │   │   ├── file2 │   │   └── file3 │   └── Crypto ├── Z │   └── Zeebra └── script.sh

itertools.groupby

输出:

from itertools import groupby

def strict_groupby(iterable, **kwargs):
    for key, group in groupby(iterable, **kwargs):
        yield (key, ''.join(group))

def consecutive_alpha(string):
    return ''.join(f'{key}#{len(group)}' 
                   if len(group) > 3 
                   else group 
                   for key, group in strict_groupby(string))

consecutive_alpha('BBBBBBCCCBBB')

答案 1 :(得分:2)

万一想要尝试单线

from itertools import groupby
''.join(_ + '#' + str(len(l)) if len(l)> 3 else ''.join(l) for l in [list(g) for _,g in groupby(str1)])
#B#6CCCBBB

答案 2 :(得分:1)

由于初始化B#5,所以得到count = 0。因此,您无需计算第一个字符。当您在循环中的稍后进行count = 1时,您将获得正确的结果。

您还有另一个问题。如果最后一个字符不是重复序列的一部分,则您永远不要打印它,因为循环会提前停止。

def consecutive_alpha(str1):
    count = 1
    new_string = ""
    n = 3
    for i in range(0, len(str1)-1):
        if str1[i] == str1[i+1]:
            count += 1
            if i == (len(str1)-2):
                if count > n:
                    new_string += str1[i] +"#" + str(count)
                else:
                    new_string += str1[i]*count
        else:
            if count > n:
                new_string += str1[i] + "#" + str(count)
            else:
                new_string += str1[i]*count
            count = 1
    # Add last character if necessary
    if len(str1) > 1 and str1[-1] != str1[-2]:
        new_string += str1[-1]
    print(new_string)

consecutive_alpha("BBBBBBCCCBBBD")
consecutive_alpha("BBBBBBCCCAAAABBBXXXXX")
相关问题