Let us suppose that we have a string and we have to calculate the total number of digits and letters present in the string.
For Example
Input −
s = “tutorialsP0int”
Output −
Letters: 13 Digits: 1
Explanation −
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.
Example
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)
Output
Running the above code will generate the output as follows −
Letters: 13 Digits: 1