- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python program to calculate the number of digits and letters in a string
Let us suppose that we have a string and we have to calculate the total number of digits and letters present in the string.
s = “tutorialsP0int”
Letters: 13 Digits: 1
Total number of letters and digits present in the given string are 13 and 1.
Approach to Solve this Problem
To calculate the total number of letters and digits in the given string, we have to first iterate over the whole string. If we get an alphabet, then we increment the letter count; otherwise, if we extract a digit, then increment the digit count.
Take an input string.
While iterating over the whole string, if we find a digit, then increment the count of digits; otherwise, if we find a letter, then increment the count of letters.
Return the count of letters and digits as the output.
str = "tutorialsP0int" digit=letter=0 for ch in str: if ch.isdigit(): digit=digit+1 elif ch.isalpha(): letter=letter+1 else: pass print("Letters:", letter) print("Digits:", digit)
Running the above code will generate the output as follows −
Letters: 13 Digits: 1
- Python Program to Calculate the Number of Words and the Number of Characters Present in a String
- C++ Program to Find the Number of Vowels, Consonants, Digits and White Spaces in a String
- Golang Program to Count the Number of Digits in a Number
- Java program to calculate the power of a number
- Write a program in Python to count the number of digits in a given number N
- Python Program to Find the Sum of Digits in a Number without Recursion
- Java Program to count letters in a String
- Calculate the Power of a Number in Java Program
- Python Program to Calculate the Length of a String Without Using a Library Function
- C++ Program to Calculate Power of a Number
- C++ Program to Sum the digits of a given number
- Program to find the sum of all digits of given number in Python
- Python Program to calculate the area of a Tetrahedron
- How to sort the letters in a string alphabetically in Python?
- PHP program to sum the digits in a number