Python Exercise: Calculate the number of digits and letters in a string
Python Conditional: Exercise-14 with Solution
Write a Python program that accepts a string and calculates the number of digits and letters.
# Prompt the user to input a string and store it in the variable 's' s = input("Input a string") # Initialize variables 'd' (for counting digits) and 'l' (for counting letters) with values 0 d = l = 0 # Iterate through each character 'c' in the input string 's' for c in s: # Check if the current character 'c' is a digit if c.isdigit(): # If 'c' is a digit, increment the count of digits ('d') d = d + 1 # Check if the current character 'c' is an alphabet letter elif c.isalpha(): # If 'c' is an alphabet letter, increment the count of letters ('l') l = l + 1 else: # If 'c' is neither a digit nor an alphabet letter, do nothing ('pass') pass # Print the total count of letters ('l') and digits ('d') in the input string 's' print("Letters", l) print("Digits", d)
Input a string W3resource Letters 9 Digits 1
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program which accepts a sequence of comma separated 4 digit binary numbers as its input and print the numbers that are divisible by 5 in a comma separated sequence.
Next: Write a Python program to check the validity of a password (input from users).
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join