检测是否有3个相同的字母相邻

2024-10-04 03:27:54 发布

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

我想检测字符串中是否有三个相同的字母相邻

例如:

string1 = 'this is oooonly excaple'   # ooo
string2 = 'nooo way that he did this' # ooo
string3 = 'I kneeeeeew it!'           # eee

有什么类似Python的方法吗? 我想这样的解决方案不是最好的:

for letters in ['aaa', 'bbb', 'ccc', 'ddd', ..., 'zzz']:
    if letters in string:
         print(True)

Tags: 字符串inthatis字母thiswayhe
3条回答

您不必使用正则表达式,但对于这样简单的事情,解决方案有点长

def repeated(string, amount):
    current = None
    count = 0
    for letter in string:
        if letter == current:
            count += 1
            if count == amount:
                return True
        else:
            count = 1
            current = letter
    return False

print(repeated("helllo", 3) == True)
print(repeated("hello", 3) == False)

使用正则表达式:

import re

pattern = r"(\w)\1{2}"

string = "this is ooonly an example"

print(re.search(pattern, string) is not None)

输出:

True
>>> 

您可以使用^{}将相似的字母分组,然后检查每组的长度:

from itertools import groupby

string = "this is ooonly an examplle nooo wway that he did this I kneeeeeew it!"
for letter, group in groupby(string):
    if len(list(group)) >= 3:
        print(letter)

将输出:

o
o
e

如果您不关心字母本身,只想知道是否有重复,请利用内置的^{}功能进行短路:

print(any(len(list(group)) >= 3 for letter, group in groupby(string)))

相关问题 更多 >