"vincent wehren" <> schrieb im Newsbeitrag
news:bs7nrc$ubp$...
| "Stormbringer" <> schrieb im Newsbeitrag
| news: om...
| | 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
|
|
|