import re str1=open('24_5.txt').read() pattern = r"^(?!.*PP).*$" result=re.findall(r'.*^(P)(\1).*$',str1) # print(max(list(map(len,result))))