How to extract digits from a string in Python and add them together?

10

I need to decompose a string into Python, separating letter and numbers, and perform the sum of these numbers. For example:

string ="96h11k"

From this string I need to extract the numbers 9, 6, 1, 1 and add them: 9 + 6 + 1 + 1 = 17. Actually, the sum is between the digits.

    
asked by anonymous 28.11.2014 / 18:19

4 answers

11

In Python, you can iterate over a string as if it were a list:

>>> for ch in string:
...   print(ch)
...
9
6
h
1
1
k

In above, each iteration ch will be a string of 1 character. To see if this character is numeric or not, you can use ch.isdigit() . To convert it to an integer, you can use int(ch) . So just add it all up:

soma = 0
for ch in string:
    if ch.isdigit():
        soma += int(ch)
print(soma)

A more concise way to do this is by using list comprehensions (or generating expressions), and the sum() (sum). For an example, see Maniero's answer .

    
28.11.2014 / 18:34
12

According to this answer in SO could use functions ready for this:

def sum_digits(digit):
    return sum(int(x) for x in digit if x.isdigit())

See running on ideone . And no Coding Ground . Also I put GitHub for future reference .

In this way you are using the sum() function whose data is generated through a list understanding where each element of the list (a string is a list of characters) is individually decomposed. >

In this case you are taking the parameter digit and analyzing each of its elements, that is, each of the characters. If the element is taken as a numeric digit (function isdigit() ) it will be delivered to the algorithm of the sum() function that knows how to add them.

You can also do it manually as shown by mgibsonbr response .

    
28.11.2014 / 18:34
3
my_string = "96h11k"
soma = sum([int(i) for i in my_string if i.isdigit()])

-------- EDIT ---------

Now that I've seen that my answer is identical to Maniero ...

For the answer is not completely useless, here's a look at generator expressions .

    
01.12.2014 / 12:56
1
fim=int(input("Digite o valor de n: "))
string = str(fim)
soma = 0
for ch in string:
    if ch.isdigit():
        soma += int(ch)
print(soma)    
    
20.01.2017 / 08:00