Python Practice › Loop Programs › Program 47
Keep only the digits of the input
Write a Python program that reads text and adds each digit to an empty list as a number.
Input
125python
Output
Enter text: 125python [1, 2, 5]
Approach
- Loop over the characters and append the digits converted with
int().
Solution
text = input("Enter text: ")numbers = []for ch in text: if ch.isdigit(): numbers.append(int(ch))print(numbers)Outputtyped input: 125python
Enter text: 125python [1, 2, 5]
Line by line
Line 4
isdigit() skips the letters.
Line 5
int(ch) stores numbers, not digit characters.
Learn the concept
New to this topic? Read the lesson, then come back.