繁体   English   中英

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

[英]How to Identify Repetitive Characters in a String Using Python?

我是 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.   

我不确定这是否适用于解决问题,任何想法如何解决这个问题?

谢谢!

您可以使用 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)]

您可以使用RegX 反向引用来做到这一点。

要在 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'”

对其他两个字符串执行相同操作,效果相同。 正则表达式可以做的远不止这些,因此请使用它们并看看它们还能做什么。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM