Shiroslullaby
Shiroslullaby

Reputation: 129

Python 3 add the total of numbers in a string which also contains letters

I have a string like:

foundstring = 'a1b2c3d4'

And want to add each number for a total like:

1+2+3+4  

So I thought I could use something like making the string to a list and a function using isdigit() to add a running total of the digits in the list like this

 listset = list(foundstring)
def get_digits_total(list1):
total = 0
for I in list1:
    if I.isdigit():
         total += I

        return total

Which gives you a list like ['a', '1', 'b', '2', 'c', '3', 'd', '4'] But that throws an error

unsupported operand type(s) for +=: 'int' and 'str'  

I know there is a very easy way to do this and Im probably making it too complicated. Im trying out some stuff with list comprehension but haven't been able to get isinstance() to do what I want so far

Upvotes: 1

Views: 273

Answers (1)

eumiro
eumiro

Reputation: 212915

Replace

total += i

with

total += int(i)

total is an integer. i is a string (always a single character from foundstring), although one of 0123456789. In order to "add" it to total, you have to convert it to an integer.

'1' + '2' = '12'  # strings
1 + 2 = 3         # integers

As a further inspiration, you can write your get_digits_total as:

total = sum(int(i) for i in foundstring if i.isdigit())

even without converting foundstring to a list, because iterating over a string returns individual characters.

Upvotes: 1

Related Questions