我想检测一个字符串中是否有三个相同的字母彼此相邻。
例如:
string1 = 'this is oooonly excaple' # ooo
string2 = 'nooo way that he did this' # ooo
string3 = 'I kneeeeeew it!' # eee
有什么pythonic方法可以做到这一点吗?我想这样的解决方案不是最好的解决方案:
for letters in ['aaa', 'bbb', 'ccc', 'ddd', ..., 'zzz']:
if letters in string:
print(True)
解决这些简单模式问题的最佳方法之一是使用正则表达式
import re
test_cases = [
'abc',
'a bbb a', # expected match for 'bbb'
'bb a b',
'aaa c bbb', # expected match for 'aaa' and 'bbb'
]
for string in test_cases:
# We use re.findall because don't want to keep only with the first result.
# In case we want to stop at the first result, we should use re.search
match = re.findall(r'(?P<repeated_characters>(.)\2{2})', string)
if match:
print([groups[0] for groups in match])
结果:
['bbb']
['aaa', 'bbb']
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句