Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to calculate the number of digits and letters in a string
Sometimes we need to count the number of digits and letters in a string separately. Python provides built-in methods like isdigit() and isalpha() to identify character types easily.
Example Input and Output
Input ?
s = "tutorialsP0int"
Output ?
Letters: 13 Digits: 1
Explanation ? The string contains 13 alphabetic characters and 1 numeric digit.
Approach
To count letters and digits in a string, we iterate through each character and use Python's built-in string methods:
Initialize counters for letters and digits
Loop through each character in the string
Use
isalpha()to check if character is a letterUse
isdigit()to check if character is a digitIncrement respective counters and display results
Using Basic Loop Method
text = "tutorialsP0int"
digit_count = letter_count = 0
for ch in text:
if ch.isdigit():
digit_count += 1
elif ch.isalpha():
letter_count += 1
print("Letters:", letter_count)
print("Digits:", digit_count)
Letters: 13 Digits: 1
Using List Comprehension
A more concise approach using list comprehension and sum() ?
text = "tutorialsP0int"
letter_count = sum(1 for ch in text if ch.isalpha())
digit_count = sum(1 for ch in text if ch.isdigit())
print("Letters:", letter_count)
print("Digits:", digit_count)
Letters: 13 Digits: 1
Function-Based Approach
Creating a reusable function to count letters and digits ?
def count_letters_digits(text):
letters = sum(1 for ch in text if ch.isalpha())
digits = sum(1 for ch in text if ch.isdigit())
return letters, digits
# Test the function
text = "Hello123World456"
letter_count, digit_count = count_letters_digits(text)
print(f"Text: {text}")
print(f"Letters: {letter_count}")
print(f"Digits: {digit_count}")
Text: Hello123World456 Letters: 10 Digits: 6
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| Basic Loop | High | Good | Beginners |
| List Comprehension | Medium | Better | Concise code |
| Function-based | High | Good | Reusable code |
Conclusion
Use isalpha() and isdigit() methods to identify character types. The basic loop approach is most readable, while list comprehension offers more concise code for counting letters and digits in strings.
