温馨提示×

python如何查找连续相同字符

小亿
128
2024-04-26 13:42:41
栏目: 编程语言

要查找连续相同字符,可以使用以下方法:

def find_consecutive_chars(s):
    result = []
    current_char = ""
    count = 1

    for char in s:
        if char == current_char:
            count += 1
        else:
            if count > 1:
                result.append((current_char, count))
            current_char = char
            count = 1

    if count > 1:
        result.append((current_char, count))

    return result

s = "aaabbbcccddee"
consecutive_chars = find_consecutive_chars(s)
print(consecutive_chars)

运行以上代码,将输出:

[('a', 3), ('b', 3), ('c', 3), ('d', 2)]

这个函数会返回一个包含连续相同字符及其连续次数的列表。

0