如何计算字符串开头的字符数?

2024-10-01 17:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,如何计算字符串开头/结尾的字符数?在

例如,如果字符串是

'ffffhuffh'

我如何计算字符串开始处的f的数目?上面带有f的字符串应该输出4。在

^{}对我没用,因为字符可能在字符串的中间。在


Tags: 字符串结尾字符数目ffffhuffh
3条回答

可以使用正则表达式与^{}一起使用正则表达式来查找字符串开头的任何字符,如下所示:

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

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

尝试使用itertools.takewhile()

import itertools as it

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

类似地,对于末尾的字符数:

^{pr2}$

一种简单的方法是使用str.lstrip方法,并计算长度差。在

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

^{}

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed.

相关问题 更多 >

    热门问题