Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...