I'm running Python 3.6.8. I need to sum values that appear in a log file. The line may contain 1 to 14 {index,value} pairs; a typical line for 8 values is in the code below(variable called 'log_line'). The line format with the '- -' separator is consistent. I have working code, but I'm not sure if this is the most elegant or best way to parse this string; it feels a bit clunky. Any suggestions?
import re
#verion 1
log_line = 'Some explanatory text was here: - -{0, 8} {1, 24} {2, 24} {3, 5} {4, 5} {5, 12} {6, 12} {7, 5}'
log_line_values = log_line.split('- -')[1]
values = re.findall(r'{\d+,\s\d+}',log_line_values)
sum_of_values = 0
for v in values:
sum_of_values += int(v.replace('{','').replace('}','').replace(' ','').split(',')[1])
print(f'1) sum_of_values:{sum_of_values}')
#verions 2, essentially the same, but more concise (some may say confusing)
sum_of_values = sum([int(v.replace('{','').replace('}','').replace(' ','').split(',')[1]) for v in re.findall(r'{\d+,\s\d+}',log_line.split('- -')[1])])
print(f'2) sum_of_values:{sum_of_values}')