Search code examples
pythonfilehandlepython-re

Why do i get an empty list when i look for numbers with regular expressions


So i've been doing an online python course and one of the assignements has me look throught a text file, find all the numbers, and print out the total sum, i am able to retrieve all the numbers however my code also returns empty lists, here's the code:

import re
handle = open('words.txt')

for line in handle:
    line = line.strip()
    numbers = re.findall('[1-9]+', line)
    print(numbers)

Solution

  • Try using \d+ (digits):

    numbers = re.findall(r'\d+', line)
    

    As for your existing regex, might be because you are missing 0 ([0-9]+).