Sum of Numbers in String

Calculate sum of all numbers in string.

AdvancedPhase 5 - Category 5: Advanced String LogicExample 5 of 14
sum-of-numbers-in-string.py
1# Take string input
2s = input("Enter a string: ")
3
4# Extract and sum numbers
5total = 0
6current_num = ""
7for char in s:
8 if char.isdigit():
9 current_num += char
10 else:
11 if current_num:
12 total += int(current_num)
13 current_num = ""
14if current_num:
15 total += int(current_num)
16
17print(f"Sum: {total}")

Output

Enter a string: Hello123World456
Sum: 579

What's going on

Extract numbers and accumulate sum.

Key Concepts:

Extract numbers from string
Convert to integers
Sum all numbers