How to count the number of characters at the beginning of a line?

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

For example, if the string

'ffffhuffh'

How do I calculate the amount fat the beginninglines? The above line with fshould output 4.

str.count not useful to me as the character may be in the middle of the line.

+4
source share
7 answers

Using the method str.lstripand calculating the length difference will be a short and simple way .

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

str.lstrip([chars]):

Returns a copy of a string with leading characters removed. Fonts An argument is a string that defines the set of characters to be deleted.

+8

, itertools.takewhile():

import itertools as it

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

, :

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

re.match, :

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

>>> len(re.match('{}*'.format(my_char), my_str).group())
4
+1

, , : reversed()

import itertools as it

my_string = 'ffffhuffh'

len(list(it.takewhile(lambda c: c == my_string[-1], reversed(my_string))))
=> 1
0

char , :

# start = True: Count the chars in the beginning of the string
# start = False: Count the chars in 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))

:

4
4
0

itertools.groupby, :

from itertools import groupby

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

:

>>> get_first_char_count('ffffhuffh')
4
>>> get_first_char_count('aywsnsb')
1
0

((^ (\ w)\2 *)), len.

len(re.sub(r'((^\w)\2*).*',r'\1',my_string))
0

Source: https://habr.com/ru/post/1677087/


All Articles