Python Practice › Loop Programs › Program 47

Keep only the digits of the input

EasyLoop Programs · 47 of 90

Write a Python program that reads text and adds each digit to an empty list as a number.

Advertisement
Input
125python
Output
Enter text: 125python
[1, 2, 5]

Approach

  1. Loop over the characters and append the digits converted with int().

Solution

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

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More loop programs

← All 90 Loop Programs