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 f
s 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.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With