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

Bengt Richter bokr at oz.net
Tue Dec 23 14:21:53 CET 2003


On 23 Dec 2003 12:57:47 GMT, bokr at oz.net (Bengt Richter) wrote:

>On 22 Dec 2003 12:04:21 -0800, andreif at mail.dntis.ro (Stormbringer) wrote:
>
>>Hi,
>>
>>Given a string s and a char c, is there a short & elegant way to
>>determine how many consecutive occurences of c are in the beginning of
>>s ?
>>
>>For example if s = ">>>>message1" and c = ">" then the number I am
>>looking for is 4 (the string begins with 4 '>').
>>
>Not tested beyond this example ;-)
>
> >>> def countleading(c, s): return len(s)-len(s.lstrip(c))
> ...
> >>> s = ">>>>message1"
> >>> countleading('>', s)
> 4
>
I wouldn't have posted this if the Re: replies had been in the same thread
tree in my reader. Guess I need to upgrade ;-/

Regards,
Bengt Richter




More information about the Python-list mailing list