w3resource

Python: Compute sum of digits of a given string


Sum digits in string.

Write a Python program to compute the sum of the digits in a given string.

Visual Presentation:

Python String: Compute sum of digits of a given string.

Sample Solution:

Python Code:

# Define a function to calculate the sum of digits in a string
def sum_digits_string(str1):
    # Initialize a variable to store the sum of digits
    sum_digit = 0

    # Iterate over each character in the string
    for char in str1:
        # Check if the current character is a digit
        if char.isdigit():
            # Convert the digit character to an integer
            digit = int(char)

            # Add the digit to the sum
            sum_digit += digit

    # Return the sum of digits
    return sum_digit

# Calculate the sum of digits in the string "123abcd45"
result1 = sum_digits_string("123abcd45")
print(result1)  # Output: 15

# Calculate the sum of digits in the string "abcd1234"
result2 = sum_digits_string("abcd1234")
print(result2)  # Output: 10 

Sample Output:

15
10

Flowchart:

Flowchart: Compute sum of digits of a given string

For more Practice: Solve these Related Problems:

  • Write a Python program to extract all digits from a string and compute their sum.
  • Write a Python program to use regular expressions to find digits in a string and sum them as integers.
  • Write a Python program to iterate over a string, convert each digit character to an integer, and return the total sum.
  • Write a Python program to implement a function that returns the sum of digits present in a given string using list comprehension.

Go to:


Previous: Write a Python program to remove duplicate characters of a given string.
Next: Write a Python program to remove leading zeros from an IP address.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.