How to Count Number of Digits, Letters, and Characters in Python


In this example, we will learn the methods to count the number of numbers, letters, and characters in a string, which can be done by using the loop sentence and judgment statements.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

str = input("Please input the string: ")
countNum = 0
countLetter = 0
countChar = 0
for i in str:
    if i.isdigit():
        countNum += 1
    elif i.isalpha():
        countLetter += 1
    countChar += 1
print("The number of digits: ", countNum)
print("The number of letters: ", countLetter)
print("The number of characters: ", countChar)

Output:

Please input the string: abc123def
The number of digits: 3
The number of letters: 6
The number of characters: 9
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
Advertisement