How To Take Out Numbers And Add Them Together In Python
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?
Solution 1:
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
Post a Comment for "How To Take Out Numbers And Add Them Together In Python"