我是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.
我不确定这是否是解决问题的适用方法,有什么想法可以解决这个问题吗?
谢谢你!
4条答案
按热度按时间wydwbb8l1#
您可以使用Counter库来计算字符最常出现的次数。
要获取单个最重复(常见)的字符,请执行以下操作:
qoefvg9y2#
您可以使用RegX backreferences来完成此操作。
x759pob23#
假设你的意思是整个字符串是一个重复的模式,this answer有一个很好的解决方案:
dddzy1tm4#
要在Python中找到一个模式,你需要使用“正则表达式”。正则表达式通常写为:
这通常跟一个if语句,以确定搜索是否成功。
例如,这是如何在字符串中找到模式“AAAA”:
这个返回
找到'AAAA'
对另外两个字符串做同样的操作,效果也是一样的。正则表达式可以做的远不止这些,所以可以使用它们,看看它们还能做什么。