Skip to main content
 首页 » 编程设计

python之连续相同字符的数量之python

2025年05月04日10TianFang

我有一个字符(例如“a”),我需要检查一个字符串(例如“aaaabcd”)中连续出现“a”的次数(在这种情况下处理停止在“b”返回值为 4)。

我有这样的东西:

def count_char(str_, ch_): 
  count = 0 
  for c in str_: 
    if c == ch_: 
      count += 1 
    else: 
      return count 

所以我在想......有没有更好/更pythonic/更简单的方法来做到这一点?

请您参考如下方法:

re.match 函数将开始查找字符串的开头

m = re.match(r'[%s]+' % ch_, str_) 
return m.end() if m else 0 

如果你想在字符串的任何部分中使用最大数量的字符:

max(len(x) for x in re.findall(r'[%s]+' % ch_, str_))