You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python实现相邻相同字符出现次数统计功能

相邻重复字符统计函数实现(Python)

需求说明

定义一个接收字符串类型参数的函数,统计该字符串中每组相邻相同字符的出现次数,函数最终返回由每个字符及对应计数拼接组成的新字符串。
示例效果:输入字符串'jjjjeerrr'时,返回结果为'j4e2r3'。

实现代码

def count_consecutive_chars(input_str: str) -> str:
    # 处理空字符串边界场景
    if not input_str:
        return ""
    
    result_parts = []
    current_char = input_str[0]
    current_count = 1

    # 从第二个字符开始遍历统计
    for char in input_str[1:]:
        if char == current_char:
            current_count += 1
        else:
            result_parts.append(f"{current_char}{current_count}")
            current_char = char
            current_count = 1
    
    # 补充最后一组字符的统计结果
    result_parts.append(f"{current_char}{current_count}")
    return "".join(result_parts)

测试调用

test_str = 'jjjjeerrr'
print(count_consecutive_chars(test_str))
# 输出结果:j4e2r3

补充说明

  • 空字符串输入会直接返回空字符串
  • 如果不需要在单字符场景显示计数1,可以修改拼接逻辑为:result_parts.append(f"{current_char}{current_count if current_count > 1 else ''}")

内容的提问来源于stack exchange,提问作者yukii Q

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 21:09:03