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

Jeff Epler jepler at unpythonic.net
Mon Dec 22 16:39:01 EST 2003


On Mon, Dec 22, 2003 at 03:16:41PM -0600, Skip Montanaro wrote:
> 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

strip() doesn't work that way:
>>> "bbbbbbbxxx".strip("bob")
'xxx'





More information about the Python-list mailing list