Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of characters at the start of a string?

How can I count the number of characters at the start/end of a string in Python?

For example, if the string is

'ffffhuffh'

How would I count the number of fs at the start of the string? The above string with a f should output 4.

str.count is not useful to me as a character could be in the middle of the string.

like image 282
caird coinheringaahing Avatar asked May 13 '17 20:05

caird coinheringaahing


3 Answers

Try this, using itertools.takewhile():

import itertools as it

s = 'ffffhuffh'
sum(1 for _ in it.takewhile(lambda c: c == 'f', s))
=> 4

Similarly, for counting the characters at the end:

s = 'huffhffff'
sum(1 for _ in it.takewhile(lambda c: c == 'f', reversed(s)))
=> 4
like image 64
Óscar López Avatar answered Oct 20 '22 17:10

Óscar López


A short and simple way will be to use the str.lstrip method, and count the difference of length.

s = 'ffffhuffh'
print(len(s)-len(s.lstrip('f')))
# output: 4

str.lstrip([chars]):

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed.

like image 30
Taku Avatar answered Oct 20 '22 16:10

Taku


You may use regular expression with re.match to find the occurrence of any character at the start of the string as:

>>> import re
>>> my_str = 'ffffhuffh'
>>> my_char = 'f'

>>> len(re.match('{}*'.format(my_char), my_str).group())
4
like image 1
Moinuddin Quadri Avatar answered Oct 20 '22 17:10

Moinuddin Quadri