I want take out the numbers then add it together for example from this:
'a12bcd3'
my answer should be 6
how do I extract the numbers and add them together?
I want take out the numbers then add it together for example from this:
'a12bcd3'
my answer should be 6
how do I extract the numbers and add them together?
Python strings are sequences; looping over them gives you individual characters. If any character is a digit (test with str.isdigit()
), turn it into an integer using int()
and sum()
those:
total = sum(int(c) for c in inputstring if c.isdigit())
Demo:
>>> inputstring = 'a12bcd3'
>>> sum(int(c) for c in inputstring if c.isdigit())
6