[SOLVED] Efficient way to check if a specific character in a string appears consecutively

Issue

Say the character which we want to check if it appears consecutively in a string s is the dot '.'.

For example, 'test.2.1' does not have consecutive dots, whereas 'test..2.2a...' has consecutive dots. In fact, for the second example, we should not even bother with checking the rest of the string after the first occurence of the consecutive dots.

I have come up with the following simple method:

def consecutive_dots(s):
    count = 0
    for c in data:
        if c == '.':
            count += 1
            if count == 2:
            return True
        else:
            count = 0
    return False

I was wondering if the above is the most ‘pythonic’ and efficient way to achieve this goal.

Solution

You can just use in to check if two consecutive dots (that is, the string "..") appear in the string s

def consecutive_dots(s):
    return '..' in s

Answered By – Aziz

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

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