HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

Shortest regex search and sum for integers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
searchshortestforsumandregexintegers

Problem

Given a text file including different text and integer numbers (text.txt), what's the shortest way of getting the sum of all the numbers out if it? I have:

import re

f = open('text.txt', 'r')
result = 0
for line in f.readlines():
    for value in re.findall('[0-9]+', line):
        result += int(value)
f.close()
print(result)


Which works, but I would like to understand what are the possibilities to make it shorter?

Solution

You can use map and sum. It good practice to use with statement when working with a file.

with open('text.txt', 'r') as f:
    result = sum(map(int, re.findall(r'[0-9]+', f.read())))

print(result)

Code Snippets

with open('text.txt', 'r') as f:
    result = sum(map(int, re.findall(r'[0-9]+', f.read())))

print(result)

Context

StackExchange Code Review Q#126363, answer score: 9

Revisions (0)

No revisions yet.