Coryza
Coryza

Reputation: 251

Python String Manipulation (SUM values)

Whats the fastest & easiest way to SUM all the numerical values before the "M's" and "I's" in this next string: "1S20M1I9M2D120M" so here we have 20M, 1I, 9M en 120M. which would be 150. Whats the easiest way to count this in Python? Because I have like +- 50000 of such strings (with all different kind of values ranging from 1 - 150), and I can't figure out an easy way.

Upvotes: 0

Views: 60

Answers (2)

Totem
Totem

Reputation: 7349

Also using regex( re.split() )

import re

s = "1S20M1I9M2D120M"
p = r'[MI]|\d+[SD]'

result = sum(int(i) for i in re.split(p, s) if i)
# re.split(p,s) => ['', '20', '1', '9', '', '120', '']
>>> print result
150

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

You can use regex for this:

>>> import re
>>> s = "1S20M1I9M2D120M"
>>> sum(int(x) for x in re.findall(r'\d+(?=[MI])', s))
150
>>> sum(int(m.group()) for m in re.finditer(r'\d+(?=[MI])', s))
150

Upvotes: 1

Related Questions