My assignment is:
"Write a function sumOfDigits that has one parameter of type string. The function should return the sum of the digits in the string. Do not treat multiple digit string as one number – “2014” should be treated as 4 different digits of 2, 0, 1, 4. The function should return 17 for the string “Today’s date is 09/01/2014”. You can assume the parameter is a string. No need to do any type validation."
Here's what I've got so far (with appropriate indentation):
def sumOfDigits (string1: str):
   summation=0
   for i in string1:
        summation=summation + int (i)
   return (summation) 
print (sumOfDigits ('543tf'))
I get the following error:
"Traceback (most recent call last):
  File "C:\Users\Andrew\Desktop\lab3.py", line 45, in <module>
    print (sumOfDigits ('543tf'))
  File "C:\Users\Andrew\Desktop\lab3.py", line 42, in sumOfDigits
    summation=summation + int (i)
ValueError: invalid literal for int() with base 10: 't'"
How do I solve this? Is it doing this because of the difficulties associated with adding an int and string/char?
The problem is that int(x) fails unless x is a digit.  The solution is to sum only the digits.  For this purpose, python has the string method isdigit.  For example:
>>> s = '543tf'
>>> sum(int(x) for x in s if x.isdigit())
12
And:
>>> s = "Today’s date is 09/01/2014"
>>> sum(int(x) for x in s if x.isdigit())
17
Unicode has added a large number of characters and python classifies some of them as digits even if int does not accept them.  One such example is superscript 3: ³.  To deal with this, python3 has introduced isdecimal and made it more discriminating than isdigit. Thus, in python3, one can use:
>>> s = "Today’s date is 09/01/2014 See footnote³"
>>> sum(int(x) for x in s if x.isdecimal())
17
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With