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

如何统计字符串中各字符出现次数并按指定格式输出?

统计字符串字符出现次数并按「数字+字符」格式输出

方法1:使用collections.Counter(简洁高效)

Python的collections.Counter可以快速统计字符出现次数,Python 3.7+中它会保留字符在原字符串中的首次出现顺序,刚好匹配需求:

from collections import Counter

input_str = 'pppeerskka'
char_counts = Counter(input_str)
output = ''.join(f"{count}{char}" for char, count in char_counts.items())
print(output)  # 输出: 3p2e1r1s2k1a

方法2:手动遍历统计(无需依赖内置库)

如果不想用内置工具,可以手动用字典记录计数,再按原字符串的字符顺序去重拼接:

input_str = 'pppeerskka'
count_dict = {}
# 统计每个字符的出现次数
for char in input_str:
    count_dict[char] = count_dict.get(char, 0) + 1

# 按首次出现顺序生成结果
output = ''
seen_chars = set()
for char in input_str:
    if char not in seen_chars:
        output += f"{count_dict[char]}{char}"
        seen_chars.add(char)

print(output)  # 输出: 3p2e1r1s2k1a

额外说明

  • 大小写区分:默认会区分大小写(比如'P'和'p'视为不同字符),若需忽略大小写,可先统一转换字符串:input_str = input_str.lower()
  • 空字符串处理:输入为空时,两种方法都会返回空字符串,符合预期

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 12:45:36