Counting repeated characters in a string in a row Python

Viewed 762

I would like to check a string for repeated characters in a row until the next space.

For example:
The following string has 4 O's in a row and I would like to detect that somehow.
myString = 'I contain foooour O's in a row without any space'

It doesnt matter what character it is as long as It's being repeated 4 times in a row without any space.

How can I achieve this and what are my options?

3 Answers

One general solution might be to use re.findall with the pattern ((\S)\2{3,}):

myString = "I contain foooour O's in a row without any space"
matches = re.findall(r'((\S)\2{3,})', myString)
print(matches[0][0])

This prints:

oooo

Try this:

myString = "I contain foooour O's in a row without any space"

def count_repeat(some_string):
    counter = 1
    max_counter = 0
    tmp = some_string[0]
    for i in range(1, len(some_string)):
        if tmp == some_string[i] and some_string[i] != " ":
            counter += 1
        else:
            max_counter = counter if max_counter < counter else max_counter
            counter = 1
        tmp = some_string[i]
    return max_counter

print(count_repeat(myString))

Output

4
import string

myString = "I contain foooour O's in a row without any space"

alphabet_lowercase = list(string.ascii_lowercase)
alphabet_uppercase = list(string.ascii_uppercase)

for index in range(26):
    if alphabet_lowercase[index] * 4 in myString:
        print(f"Found {alphabet_lowercase[index]}")
    if alphabet_uppercase[index] * 4 in myString:
        print(f"Found {alphabet_uppercase[index]}")

The above code will display any character that is repeated 4 times in a row. It will print the character that is repeated.

Related