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.
1# Take string input2s = input("Enter a string: ")34# Extract numbers5numbers = []6current_num = ""7for char in s:8 if char.isdigit():9 current_num += char10 else:11 if current_num:12 numbers.append(int(current_num))13 current_num = ""14if current_num:15 numbers.append(int(current_num))1617print(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
Append digit characters to current_num.
- 2
On a nondigit, convert and append any buffered run.
- 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].
๐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