Sebastian Rios
Sebastian Rios

Reputation: 5

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)

Upvotes: 0

Views: 124

Answers (1)

Ronie Martinez
Ronie Martinez

Reputation: 1275

Try using \d+ (digits):

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

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

Upvotes: 0

Related Questions