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.
1# Take string input2s = input("Enter a string: ")34# Count digits5count = 06for char in s:7 if char.isdigit():8 count += 1910print(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
Visit every character of s.
- 2
Increment count when char.isdigit is true.
- 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.
๐Related Content
- ๐
Phase 5 - Learn Concepts
Review Phase 5 concepts and explanations
- ๐
Phase 5 - Quiz
Test your Phase 5 understanding with quiz questions
- ๐ป
Phase 5 - All Practice Problems
Explore all practice problems for Phase 5
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum