How can Python search for consecutive identical characters?

You can iterate through each character in a string using a loop, checking if it is the same as the previous character. If it is, add it to a list. If it is different, convert the consecutive same characters in the list to a string and add it to another list. Finally, return the consecutive same character strings in the second list.

Here is an example code:

def find_consecutive_chars(string):
    consecutive_chars = []
    current_consecutive = string[0]

    for char in string[1:]:
        if char == current_consecutive[-1]:
            current_consecutive += char
        else:
            consecutive_chars.append(current_consecutive)
            current_consecutive = char

    consecutive_chars.append(current_consecutive)

    return consecutive_chars

# 示例用法
string = "aaabbbcccdddeee"
result = find_consecutive_chars(string)
print(result)  # ['aaa', 'bbb', 'ccc', 'ddd', 'eee']

In this example, we defined a function find_consecutive_chars that takes a string as input. We initialized two empty lists, consecutive_chars for storing consecutive same characters strings, and current_consecutive for storing the currently checked consecutive characters. We assigned the first character of the string to current_consecutive. Then, we used a loop to iterate over each character of the string starting from the second character. If the current character is the same as the last character of current_consecutive, we add it to current_consecutive. If it is different, it means we have found a consecutive same character string, so we add it to consecutive_chars and reset current_consecutive to the current character. Finally, we also need to add the last consecutive same character string to consecutive_chars and return it.

I hope this can help you!

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds