简体   繁体   中英

Python: Count the consecutive characters at the beginning of a string

I want to count how many leading repeat characters at the beginning of a string. So far the code I wrote:

def count_characters(s, target):
    counter = 0
    for i in range(len(s)):
        if s[i] == target:
            counter += 1
        else:
            return counter

It works. Now I just curious if there is a simpler way to get it done in one or two lines instead of writing an extra function?

If you strip the characters from the beginning, then you are left with a shorter string and can subtract its length from the original, giving you the number of characters removed.

return len(s) - len(s.lstrip(target))


Note: Your shown code will immediately return 0 if the first character does not match target . If you want to check if there is any repeated first character, you don't need to have target and can just use s[0]

You could use next and a range :

return next(i+1 for i in range(len(s)) if s[i] != s[0], len(s))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM