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

Question:

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.

Answers:

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
Answered By: Moinuddin Quadri

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
Answered By: Óscar López

Building on Oscar Lopez’s answer, I want to handle the case you mention of the end of the string: use reversed()

import itertools as it

my_string = 'ffffhuffh'

len(list(it.takewhile(lambda c: c == my_string[-1], reversed(my_string))))
=> 1
Answered By: Arya McCarthy

You can create a function and iterate through your string and return the count of the desired char in the input string’s beginning or end like this example:

# start = True: Count the chars at the beginning of the string
# start = False: Count the chars at the end of the string
def count_char(string= '', char='', start=True):
    count = 0
    if not start:
        string = string[::-1]

    for k in string:
        if k is char:
            count += 1
        else:
            break
    return count

a = 'ffffhuffh'
print(count_char(a, 'f'))
b = a[::-1]
print(count_char(b, 'f', start=False))

Output:

4
4
Answered By: Chiheb Nexus

You may also use itertools.groupby to find the count of the occurrence of the first element at the start of the string as:

from itertools import groupby

def get_first_char_count(my_str):
    return len([list(j) for _, j in groupby(my_str)][0])

Sample run:

>>> get_first_char_count('ffffhuffh')
4
>>> get_first_char_count('aywsnsb')
1
Answered By: Moinuddin Quadri

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.

Answered By: Taku

re.sub select first letter with repeat( (^(w)2*) ), len count frequency.

len(re.sub(r'((^w)2*).*',r'1',my_string))
Answered By: Shenglin Chen
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.