Counting how many chars equal to a given char are in the beginning of a string

Skip Montanaro skip at pobox.com
Mon Dec 22 16:16:41 EST 2003


    Andrei> Given a string s and a char c, is there a short & elegant way to
    Andrei> determine how many consecutive occurences of c are in the
    Andrei> beginning of s ?

    Andrei> For example if s = ">>>>message1" and c = ">" then the number I
    Andrei> am looking for is 4 (the string begins with 4 '>').

How about:

    def howmanyatstart(s, pfx):
        return (len(s) - len(s.lstrip(pfx)))/len(pfx)

?  This works for prefixes which are longer than a single character:

    >>> howmanyatstart(">>>>message1", '>')
    4
    >>> howmanyatstart("bobbobbob>>>>message1", 'bob')
    3

Skip





More information about the Python-list mailing list