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

vincent wehren vincent at visualtrans.de
Mon Dec 22 16:38:25 EST 2003


"vincent wehren" <vincent at visualtrans.de> schrieb im Newsbeitrag
news:bs7nrc$ubp$1 at news1.tilbu1.nb.home.nl...
| "Stormbringer" <andreif at mail.dntis.ro> schrieb im Newsbeitrag
| news:21bb8d55.0312221204.51d86182 at posting.google.com...
| | 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 '>').
|
| How about:
|
| def getc(s, c):
|     """
|     Get the number of consecutive occurrences of given char c
|     at the beginning of given string s.
|     """
|     cnt = 0
|     while 1:
|         try:
|            if s[cnt] == c:
|                cnt += 1
|            else:
|                return cnt
|         except IndexError:
|            return cnt
|
| c = '>'
| print getc(">>>>Message", c) #prints 4
| print getc(" >>>>Message", c) #prints 0
| print getc (">>>", c) #prints 3
|
| Maybe not the most elegant or shortest, but it works...

Looking at Jeff's proposed solutions, I would like to  replace
the "Maybe" part in the above sentence with "Definitively"...

Isn't Python great?

Vincent




  Vincent Wehren


|
| HTH,
|
| Vincent Wehren
|
|
| |
| | Thanks,
| | Andrei
|
|






More information about the Python-list mailing list