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
Run in browser1# 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.