如何使用Python识别字符串中的重复字符?

mjqavswn  于 2023-05-16  发布在  Python
关注(0)|答案(4)|浏览(177)

我是python的新手,我想写一个程序来确定一个字符串是否由重复字符组成。我想测试的字符串列表是:

  • Str1 =“AAAA”
  • Str2 =“AGAGAG”
  • Str3 =“AAA”

我得到的伪代码:

WHEN len(str) % 2 with zero remainder:
- Divide the string into two sub-strings. 
- Then, compare the two sub-strings and check if they have the same characters, or not.
- if the two sub-strings are not the same, divide the string into three sub-strings and compare them to check if repetition occurs.

我不确定这是否是解决问题的适用方法,有什么想法可以解决这个问题吗?
谢谢你!

wydwbb8l

wydwbb8l1#

您可以使用Counter库来计算字符最常出现的次数。

>>> from collections import Counter
>>> s = 'abcaaada'
>>> c = Counter(s)
>>> c.most_common()
[('a', 5), ('c', 1), ('b', 1), ('d', 1)]

要获取单个最重复(常见)的字符,请执行以下操作:

>>> c.most_common(1)
[('a', 5)]
qoefvg9y

qoefvg9y2#

您可以使用RegX backreferences来完成此操作。

x759pob2

x759pob23#

假设你的意思是整个字符串是一个重复的模式,this answer有一个很好的解决方案:

def principal_period(s):
    i = (s+s).find(s, 1, -1)
    return None if i == -1 else s[:i]
dddzy1tm

dddzy1tm4#

要在Python中找到一个模式,你需要使用“正则表达式”。正则表达式通常写为:

match = re.search(pat, str)

这通常跟一个if语句,以确定搜索是否成功。
例如,这是如何在字符串中找到模式“AAAA”:

import re

string = ' blah blahAAAA this is an example'
match = re.search(r 'AAAA', string)

if match:
    print 'found', match.group()
else :
    print 'did not find'

这个返回
找到'AAAA'
对另外两个字符串做同样的操作,效果也是一样的。正则表达式可以做的远不止这些,所以可以使用它们,看看它们还能做什么。

相关问题