Given a string as input to the Python program, the program should accept the string, iterate all the characters present in the string and count the number of digits and number of letters present in the string
Print the count of of digits and letter in a string
Write a Python Program That Accepts a String And Calculate The Number of Digits And Letters
Let's take a variable named data, to using input function call let's ask a user to enter a string
data = input("Enter a String : ")
Now take two variable to store The Count of digits and count of letters and initialize both the variables to
digit_count, letter_count = 0, 0
Using the for loop, iterate all the letters present in the string and check if the letter is between a to z or between capital A to Z. If so, increment the letter count by 1.
Take if else block, check if the letter is between 0 to 9 and increment the digit count by 1. Once the for loop ends we will be having the count of digits and letters stored in the variables. use the print statement to print the count of digits and letters
for item in data:
if 'a' <= item <= 'z' or 'A' <= item <= 'Z':
letter_count += 1
elif '0' <= item <= '9':
digit_count += 1
print("Count of Digits is : ", digit_count)
print("Count of Letters is : ", letter_count)
final program
====================
data = input("Enter a String : ")
digit_count, letter_count = 0, 0
for item in data:
if 'a' <= item <= 'z' or 'A' <= item <= 'Z':
letter_count += 1
elif '0' <= item <= '9':
digit_count += 1
print("Count of Digits is : ", digit_count)
print("Count of Letters is : ", letter_count)
Output
================
Enter a String : call@111
Count of Digits is : 3
Count of Letters is : 3
Output
================
Enter a String : hello world
Count of Digits is : 0
Count of Letters is : 10
Other variant
==================
The above program can also be modified and written using the built-in functions isalpha() and isdigit() To check for character is alphabet or digit. below is a program
data = input("Enter a String : ")
digit_count, letter_count = 0, 0
for item in data:
if item.isalpha():
letter_count += 1
elif item.isdigit():
digit_count += 1
print("Count of Digits is : ", digit_count)
print("Count of Letters is : ", letter_count)
Conclusion
================
Try running the program by providing different set of string input values and evaluate the results.
0 Comments