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

Count Digits in String

Count digit characters inside mixed text with isdigit. Students scan a string without int conversion and distinguish this task from counting an integer's places.

BeginnerPhase 5 - Category 2: Character OperationsExample 6 of 10
count-digits-in-string.py
1# Take string input
2s = input("Enter a string: ")
3
4# Count digits
5count = 0
6for char in s:
7 if char.isdigit():
8 count += 1
9
10print(f"Digits: {count}")

Output

Enter a string: Hello123
Digits: 3

In this one

  • Scan digits inside mixed text
  • Preserve leading zeros
  • Avoid converting the whole input

How it works

  1. 1

    Visit every character of s.

  2. 2

    Increment count when char.isdigit is true.

  3. 3

    Print the digit-character count.

Edge cases

Does A007 count three digits?

Does A007 count three digits?

Yes. All three digit characters remain in the text.

Does a minus sign count?

Does a minus sign count?

No. It is not a digit.

What's going on

This program counts characters such as the 2 in room2, not the decimal positions of an entered integer. The source remains text throughout.

Each char.isdigit() match adds one, so A007 contains three digit characters and preserves its leading zeros. Signs and decimal points are not digits. Unicode digit characters can qualify beyond ASCII, which matters if the result is later used for numeric parsing.

Does A007 count three digits? Yes. All three digit characters remain in the text.

Does a minus sign count? No. It is not a digit.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why avoid int(s) here?

Pick an answer to check it.

Question 2

Does A007 count three digits?

Pick an answer to check it.

Questions people ask

Does A007 count three digits?

Yes. All three digit characters remain in the text.

Does a minus sign count?

No. It is not a digit.

Why avoid int(s) here?

Mixed text is not an integer, and leading zeros matter.