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

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.

IntermediatePhase 6 - Category 2: Array & String CombinationsExample 2 of 10
convert-string-to-array-of-digits.py
1# Take string
2s = input("Enter a string of digits: ")
3
4# Convert to array
5arr = [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. 1

    Visit every source character.

  2. 2

    Keep characters passing isdigit and convert each separately.

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