Skip to content Skip to sidebar Skip to footer

No Output From Sum Of Python Regex List

The problem is to read the file, look for integers using the re.findall(), looking for a regular expression of '[0-9]+' and then converting the extracted strings to integers and su

Solution 1:

You need to append the find results to another list. So that the number found on current line will be kept back when iterating over to the next line.

import re
hand = open('sample.txt')
l = []
for line in hand:
    x = re.findall('[0-9]+',line)
    l.extend(x)


j = [int(i) for i in l]
add = sum(j)
print add

or

withopen('sample.txt') as f:
    printsum(map(int, re.findall(r'\d+', f.read())))

Solution 2:

try this

import re
hand = open("a.txt")
x=list()
for line in hand:
    y = re.findall('[0-9]+',line)
    x = x+y

sum=0for z in x:
    sum = sum + int(z)

print(sum)

Post a Comment for "No Output From Sum Of Python Regex List"