Reputation: 922
How would I go about splitting a string up and then adding up the integers inside, with the code below I am able to add up single integers, but if I get a string like "a12b34" I should be able to do 12 + 34 not 1+2+3+4 like the code below does. I am able to do this in C but I do not know how to 100% do it in python.
strTest = str(raw_input("Enter an alphanumeric string: "))
total = 0
for ch in strTest:
if ch.isdigit() == True:
total = total + int(ch)
print total
Upvotes: 0
Views: 957
Reputation: 10951
User re.findall
to extract all digits, convert them to integer and then sum the results
>>> import re
>>> s = 'a12b34'
>>> total = sum(map(int,re.findall(r'-?\d+', s))) # -? is to cover negative values
46
This is valid only if you have integers
EDIT:
For general cases, where you might have float number as well, consider the following:
>>> s = 'a12b32c12.0d11.455'
>>> sum(map(float, re.findall(r'-?\d+\.?\d+', s)))
67.455
>>> s = 'a12b-32c12.0d-11.455'
>>> sum(map(float, re.findall(r'-?\d+\.?\d+', s)))
-19.455
EDIT2:
So what's happening:
1 - import re
will import and load re
module, which is a module used to extract complex string format based on the provided pattern. More details here
2 - re.findall
will return all matching string in s
with the provided pattern r'-?\d+\d.>\d+'
3 - The pattern r'-?\d+\d.>\d+
breakdown (which can be found here):
4 - Now, re.findall
will return a list of all matches:
>>> s = 'a12b-32c12.0d11.455'
>>> re.findall(r'-?\d+\.?\d+', s)
['12', '-32', '12.0', '11.455']
5 - map
will convert each element from this list from string into float returning a generator:
>>> map(float, re.findall(r'-?\d+\.?\d+', s))
<map object at 0x0000000003873470>
>>> list(map(float, re.findall(r'-?\d+\.?\d+', s)))
[12.0, -32.0, 12.0, -11.455]
6 - Passing the result of map
to sum
will sum all elements to their total:
>>> sum([12.0, -32.0, 12.0, -11.455])
-19.455
Upvotes: 3