要查找連續相同字符,可以使用以下方法:
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)]
這個函數會返回一個包含連續相同字符及其連續次數的列表。