Write a Python program to compute sum of digits of a given string
The program is written in Python and it performs the following operations:
- In the first line, a string "Hello World 2345" is assigned to the variable "str1".
- In the second line, a variable "sum_num" is initialized to 0, which will be used to keep track of the sum of all the digits in the string.
- In the third line, a for loop is used to iterate over each character in the "str1" string.
- In the fourth line, the "isdigit" method is used to check if the current character is a digit. If it is, the "int" function is used to convert the character to an integer, and the result is stored in the variable "z".
- In the fifth line, the value of "z" is added to the "sum_num" variable, which keeps track of the sum of all the digits in the string.
- The final line uses the "print" function to print the value of "sum_num", which is the sum of all the digits in the string.
In summary, this program demonstrates how to sum all the digits in a string by iterating over each character, checking if it's a digit, and adding it to a running total if it is.
Source Code
str1 = "Hello World 2345"
sum_num = 0
for x in str1:
if x.isdigit() == True:
z = int(x)
sum_num = sum_num + z
print(sum_num)
Output
14