在Python中从字符串中删除特定数量的重复字母

2024-09-26 17:47:03 发布

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

我试图从一个字符串中删除特定数量的重复字母并显示该字符串。 例如,我有一个类似“sdfgsd sdfd jkhj dfg sdf”的字符串,我想从这个字符串中删除3次或更多次重复的字母,然后再次显示 我怎样才能做到这一点。这是我的代码:

chars = "abcdefghijklmnopqrstuvwxyz"
    check_string = "aanbg sdfsd futy asdf sdferg gyıuy"
    for char in chars:
        count = check_string.count(char)
//3 and more than 3 times repeated letters removing from string
        if count >= 3:
        remove (char, count)
        print("check_string")

Tags: 字符串代码数量stringcheckcount字母sdf
1条回答
网友
1楼 · 发布于 2024-09-26 17:47:03

这应该是有效的:

>>> from collections import Counter

>>> check_string = "aanbg sdfsd futy asdf sdferg gyıuy"
>>> letter_occurrances = Counter(check_string).items()
>>> letter_occurrances
dict_items([('a', 3), ('n', 1), ('b', 1), ('g', 3), (' ', 5), ('s', 4), ('d', 4), ('f', 4), ('u', 2), ('t', 1), ('y', 3), ('e', 1), ('r', 1), ('ı', 1)])    
>>> for key, value in letter_occurrances:
       if value>=3 and key!=' ':
          check_string = check_string.replace(key, '')
>>> check_string
'nb  ut  er ıu'    

如果您想自己实现letter_occurrances

^{pr2}$

相关问题 更多 >

    热门问题