Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

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.

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

In this one

  • Convert whole digit runs
  • Add on boundary transitions
  • Treat signs as separators

How it works

  1. 1

    Build current_num across adjacent digits.

  2. 2

    At separators, convert and add the buffer, then clear it.

  3. 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.