python如何查看某一个字符串中字符首先出现3次的方法

2025-06-23 05:57:37
推荐回答(1个)
回答1:

可以遍历字符串,统计各字符出现的次数,次数达到3则打印

from collections import defaultdict
s = 'baidu zhidao zhidao baidu'

d = defaultdict(lambda :0)
for char in s:
    d[char] += 1
    if d[char] == 3:
        print(char)
        break