Convert String to Array of Digits
Convert digit characters in mixed text into a integer list. Students follow a filtered comprehension and distinguish individual digits from whole-number runs.
1# Take string2s = input("Enter a string of digits: ")34# Convert to array5arr = [int(char) for char in s if char.isdigit()]6print(f"Array: {arr}")
Output
Enter a string of digits: 12345 Array: [1, 2, 3, 4, 5]
In this one
- Filter individual characters
- Convert single digits
- Distinguish runs from positions
How it works
- 1
Visit every source character.
- 2
Keep characters passing isdigit and convert each separately.
- 3
Store those values in arr and print it.
Edge cases
Does a12 produce twelve?
Does a12 produce twelve?
No. It produces separate one and two entries.
What happens for no digits?
What happens for no digits?
The result is an empty list.
What's going on
The comprehension visits every character and keeps those passing isdigit. int converts each retained character separately.
Thus a12b3 becomes [1, 2, 3], not [12, 3]. Nondigits are skipped rather than rejected. Leading zeros become integer zeros. Some Unicode characters satisfy isdigit but cannot be parsed by int, so this convenient filter is not a fully general Unicode-number parser.
Does a12 produce twelve? No. It produces separate one and two entries.
What happens for no digits? The result is an empty list.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What does the comprehension convert?
Pick an answer to check it.
Question 2
Does a12 produce twelve?
Pick an answer to check it.
Questions people ask
Does a12 produce twelve?
No. It produces separate one and two entries.
What happens for no digits?
The result is an empty list.
What does the comprehension convert?
Each selected character.
๐Related Content
- ๐
Phase 6 - Learn Concepts
Review Phase 6 concepts and explanations
- ๐
Phase 6 - Quiz
Test your Phase 6 understanding with quiz questions
- ๐ป
Phase 6 - All Practice Problems
Explore all practice problems for Phase 6
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum