'Extract two numbers form a string and add them together

This is probably very simple but I find that I'm confused. I have the following string:

output = ['traff-05-2021=38540:2120 33078:1799 38785:2022 31420:1759 41613:2220 31805:1908 37151:2055 42374:2252 45631:2335 42688:2099 46200:2283 40684:2188 22394:1117 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 0:0 [492363:26157]\n']

What I would like to do is to extract the last two numbers in the string (492363 and 26157 in the above example), add them together and save the sum as "traffic". I will then write the value "traffic" to a text file. The numbers in the string will constantly change but the placement will always be the same.

Would someone please help me with the correct syntax? Thanks!



Solution 1:[1]

You could use reduce and regular expressions as follows.

traffic = reduce(lambda a,b: int(a)+int(b), re.search(r'\[(.*?)\]',output[0]).group(1).split(":"))

We use \[(.*?)\] to match everything between square brackets and then split the string into an array using : as a delimiter. Then, we use reduce to reduce everything to a single value by summing them up.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Scholz