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

Extract Numbers from String

Extract runs of digit characters as integers from mixed text. Students buffer adjacent digits, flush on separators, and handle a number without a separator.

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

Output

Enter a string: Hello123World456
Numbers: [123, 456]

In this one

  • Buffer adjacent digit characters
  • Flush at separators
  • Include a trailing run

How it works

  1. 1

    Append digit characters to current_num.

  2. 2

    On a nondigit, convert and append any buffered run.

  3. 3

    After traversal, flush a remaining run and print numbers.

Edge cases

Why flush after the loop?

Why flush after the loop?

The last digit run may have no following separator.

Does -12 become a negative integer?

Does -12 become a negative integer?

No. The minus sign is treated as a separator.

What's going on

current_num collects consecutive digit characters. A nondigit ends that run, converts it with int, appends it, and clears the buffer.

The final if handles a run that reaches the end of the input. For a12b3, the result is [12, 3]. Signs and decimal points split runs rather than becoming part of a number. Some Unicode isdigit characters are not accepted by int, a parsing limitation.

Why flush after the loop? The last digit run may have no following separator.

Does -12 become a negative integer? No. The minus sign is treated as a separator.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What does a12b3 produce?

Pick an answer to check it.

Question 2

Why flush after the loop?

Pick an answer to check it.

Questions people ask

Why flush after the loop?

The last digit run may have no following separator.

Does -12 become a negative integer?

No. The minus sign is treated as a separator.

What does a12b3 produce?

[12, 3].