Sum of Numbers in String
Sum whole-number digit runs embedded in text with Python. Students buffer adjacent digits, add completed values, and distinguish numbers from digit characters.
1# Take string input2s = input("Enter a string: ")34# Extract and sum numbers5total = 06current_num = ""7for char in s:8 if char.isdigit():9 current_num += char10 else:11 if current_num:12 total += int(current_num)13 current_num = ""14if current_num:15 total += int(current_num)1617print(f"Sum: {total}")
Output
Enter a string: Hello123World456 Sum: 579
In this one
- Convert whole digit runs
- Add on boundary transitions
- Treat signs as separators
How it works
- 1
Build current_num across adjacent digits.
- 2
At separators, convert and add the buffer, then clear it.
- 3
Add any final buffered number and print total.
Edge cases
Why add after the loop too?
Why add after the loop too?
A final number may end at the last character.
What does -12 contribute?
What does -12 contribute?
Positive twelve, since the sign is not included.
What's going on
Consecutive digit characters build current_num. When a separator arrives, the buffered run is converted and added to total.
A final flush includes a trailing number. For a12b3, the total is fifteen, not six from adding separate digits. Minus signs and decimal points are separators here, so this is not a signed-decimal parser. Unicode digit classification can also exceed what int accepts.
Why add after the loop too? A final number may end at the last character.
What does -12 contribute? Positive twelve, since the sign is not included.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the total for a12b3?
Pick an answer to check it.
Question 2
Why add after the loop too?
Pick an answer to check it.
Questions people ask
Why add after the loop too?
A final number may end at the last character.
What does -12 contribute?
Positive twelve, since the sign is not included.
What is the total for a12b3?
15.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum