I am working through John Guttag's 'Introduction to Computation and Programming Using Python' and encountered an exercise to create a function that returns the sum of decimal digits in a string. I have been able to implement this for single-digit int > 0. Do point out if my code is somehow inefficient or if it could be made more pythonic.
I want to take this further than simply summing single digits in the str (combination of characters, not just digits, without delimiters between 'numbers' to be summed).
If a 'number' is defined as a sequence of digits without intervening non-digit characters (other than . to represent floats), how can the function be extended to recognise and sum multiple-digit numbers, negative numbers like -5 and floats like 1.23?
Here is my code:
def sumDigits(s):
"""Assumes s an str
Returns sum of digits in s"""
w= []
for i in range(len(s)):
try:
w.append(int(s[i]))
except ValueError:
w.extend('')
sum = 0
for x in w:
sum += x
print('sumDigits is:', sum)
sumDigits(str(input('Enter sequence:')))