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

count, python, python-3.x, string

Solution

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.

Problem

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.

Original source