# Sum the digits in a string in Python Last updated: Jul 4, 2022 Photo from Unsplash

## Sum the digits in a string in Python#

To sum the digits in a string in Python:

1. Use a generator expression to iterate over the string.
2. On each iteration, convert each character to an integer if it is a digit.
3. Use the `sum()` function to get the sum of the digits.
main.py
```Copied!```my_str = '1ab2c3'

# ✅ sum digits in a string that might contain non-digits
total = sum(int(char) for char in my_str if char.isdigit())

print(total)  # 👉️ 6

# -----------------------------------------------------------

# ✅ sum digits in a string that contains only digits

my_str_2 = '246'

total_2 = sum(int(d) for d in my_str_2)

print(total_2)  # 👉️ 12
``````

We used a generator expression to iterate over the string.

Generator expressions are used to perform some operation for every element, or select a subset of elements that meet a condition.

On each iteration, we check if the character is a digit.

The str.isdigit method returns `True` if all characters in the string are digits and there is at least 1 character, otherwise `False` is returned.

We convert all digits to integers and use the `sum()` function to get the total.

main.py
```Copied!```my_str = '1ab2c3'

# ✅ sum digits in a string that might contain non-digits
total = sum(int(char) for char in my_str if char.isdigit())

print(total)  # 👉️ 6
``````

The last step is to use the `sum()` function to sum the numbers in the generator object.

The sum function takes an iterable, sums its items from left to right and returns the total.

The `sum` function takes the following 2 arguments:

NameDescription
iterablethe iterable whose items to sum
startsums the `start` value and the items of the iterable. `sum` defaults to `0` (optional)

If your string is guaranteed to only contain digits, you don't have to use the `str.isdigit()` method.

main.py
```Copied!```# ✅ sum digits in a string that contains only digits

my_str_2 = '246'

total_2 = sum(int(d) for d in my_str_2)

print(total_2)  # 👉️ 12
``````
I wrote a book in which I share everything I know about how to become a better, more efficient programmer. You can use the search field on my Home Page to filter through all of my articles.