Python program to calculate the number of digits and letters in a string
Last Updated :
09 Jan, 2025
Improve
In this article, we will check various methods to calculate the number of digits and letters in a string. Using a for loop to remove empty strings from a list involves iterating through the list, checking if each string is not empty, and adding it to a new list.
s = "Hello123!"
# Initialize counters for letters and digits
l_c = 0
d_c = 0
# Iterate through each character in the string
for char in s:
# Check if the character is a letter
if char.isalpha():
l_c += 1
# Check if the character is a digit
elif char.isdigit():
d_c += 1
print(f"Letters: {l_c}")
print(f"Digits: {d_c}")
Output
Letters: 5 Digits: 3
Explanation
for
loop iterates through each character in the strings
, usingchar.isalpha()
to check if a character is a letter andchar.isdigit()
to check if it is a digit.- counters
l_c
andd_c
are incremented based on the character type, and the final counts of letters and digits are printed.
Using filter()
Using filter()
to remove empty strings from a list allows you to apply a filtering condition, such as checking whether each string is non-empty, and return a list of only the strings that meet the condition.
s = "Hello123!"
# Count letters using filter and len
l_c = len(list(filter(str.isalpha, s)))
# Count digits using filter and len
d_c = len(list(filter(str.isdigit, s)))
print(f"Letters: {l_c}")
print(f"Digits: {d_c}")
Output
Letters: 5 Digits: 3
Explanation
filter(str.isalpha, s)
filters out only the alphabetic characters from the strings
, andlen(list(...))
counts the number of alphabetic characters.filter(str.isdigit, s)
filters out the digits, andlen(list(...))
counts the number of digits in the string, with both counts being printed.
Using collections.Counter
Using collections.Counter
to count the number of letters and digits in a string allows to check the occurrences of each character. The Counter
class creates a dictionary-like object where characters are keys, and their counts are values.
from collections import Counter
# Input string
s = "Hello123!"
# Count frequencies of each character
f = Counter(s)
# Count letters and digits
l_c = sum(1 for char in f if char.isalpha())
d_c = sum(1 for char in f if char.isdigit())
# Print the counts
print(f"Letters: {l_c}")
print(f"Digits: {d_c}")
Output
Letters: 4 Digits: 3
Explanation
- The
Counter(s)
counts the frequency of each character in the strings
, storing the results in aCounter
objectf
. - The
sum(1 for char in f if char.isalpha())
counts the number of alphabetic characters, andsum(1 for char in f if char.isdigit())
counts the number of digits in the string, with the counts being printed.