To find three words in a row in a line and display them:
words = text.split() for triple in zip(words, words[1:], words[2:]): if all(s.isalpha() for s in triple): print(*triple) break else: print("not found")
This is straightforward for Python programmer code, but it performs unnecessary copying and comparison.
Here is the code that is similar to the solution that uses the count from the @Alexcei Shmakov answer — this option prints the three words itself, and not only is it on the line, like the count solution:
triple = [] for s in text.split(): if s.isalpha(): triple.append(s) if len(triple) == 3: print(*triple) break else: del triple[:] # empty else: print("not found")
In order not to create a possibly large list of strings separated by a space, you can use regular expressions:
import re m = re.search(r'\s+'.join([r'[^\d\s]+']*3), text) print(m.group() if m else "not found")
This option looks for characters that are not numbers, spaces (which is suitable for setting the problem in question), since the re module does not support the analog str.isalpha . regex module supports \p{Letter} .
Measurements can show whether there is a performance difference for the actual input.