Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add numbers and letters in a string in Python3.3.5 (The final result should be an int)?

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?

like image 473
AndyM3 Avatar asked Oct 11 '14 00:10

AndyM3


1 Answers

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

Python3

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
like image 115
John1024 Avatar answered Sep 25 '22 17:09

John1024