with open('polish_wiki_excerpt.in', encoding='utf8') as f: lines = f.readlines() results = [] i = 0 for line in lines: line = line.strip() subdigits = [] pom = '' for char in line: if char in '0123456789': pom += char elif pom != '': subdigits.append(pom) pom = '' else: pass if pom.isdigit(): subdigits.append(pom) if len(subdigits) > 0: finalLine = ' '.join(subdigits) print(finalLine)