[英]How to count the number of characters at the start of a string?
一個簡短的方法是使用str.lstrip
方法,並計算長度的差異。
s = 'ffffhuffh'
print(len(s)-len(s.lstrip('f')))
# output: 4
返回刪除了前導字符的字符串副本。 chars參數是一個字符串,指定要刪除的字符集。
試試這個,使用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
您可以使用帶有re.match
正則表達式來查找字符串開頭的任何字符的出現位置:
>>> import re
>>> my_str = 'ffffhuffh'
>>> my_char = 'f'
>>> len(re.match('{}*'.format(my_char), my_str).group())
4
基於Oscar Lopez的回答,我想處理你提到的字符串結尾的情況:使用reversed()
import itertools as it
my_string = 'ffffhuffh'
len(list(it.takewhile(lambda c: c == my_string[-1], reversed(my_string))))
=> 1
您可以創建一個函數並遍歷您的字符串,並在輸入字符串的開頭或結尾返回所需字符的計數,如下例所示:
# 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
您還可以使用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
re.sub選擇帶重復的第一個字母((^(\\ w)\\ 2 *)),len計數頻率。
len(re.sub(r'((^\w)\2*).*',r'\1',my_string))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.