Skip to main content
 首页 » 编程设计

python之在字符串中查找连续的字母

2025年05月04日35xing901022

我想找到连续的字符数并将它们打印为>3个字母#count否则打印所有字母 我想得到: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) 

请您参考如下方法:

为什么不直接使用 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') 

输出:

'B#6CCCBBB'