Unix -Python-courses-Solaris, Linux, FreeBSDPython-courses-python-exercises-python

Exercise 63

Write a Python program that calculates the sum of digits numbers within a given string.

Solution

def digitSum(s):
# initializing the sum of digits within the string s.
sumDigit = 0

# iterate over all characters of s:
for x in s:
if x.isdigit():

# convert x into int type
x = int(x)

# adding x to sumDigit
sumDigit = sumDigit + x

return sumDigit

#Testing algorithm:
s = "Python3.8 is more powerful than Python 2.7 "
print("The sum of digits within the string s is :" , digitSum(s))
# The output is :
# The sum of digits within the string s is : 20

Younes Derfoufi
my-courses.net

Leave a Reply