Count Digits in String in Python
Count how many digit characters appear in a string.
BeginnerString ProgramsExample 5 of 25
count-digits-in-string.py
1# Program to count digits in a string23s = input("Enter a string: ")45count = sum(1 for ch in s if ch.isdigit())67print("Number of digits:", count)
Output
Enter a string: a1b2c3 Number of digits: 3
What's going on
We use .isdigit() to detect numeric characters and count them.
After this program
If the idea is still fuzzy, read Day 4: Strings and String Methods in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 string programs, or see every topic on Python exercises.