Knowee
Questions
Features
Study Tools

Python program that accepts a string and calculate the number of digits and letters and space

Question

Python program that accepts a string and calculate the number of digits and letters and space

🧐 Not the exact question you are looking for?Go ask a question

Solution

Sure, here is a Python program that calculates the number of digits, letters and spaces in a given string:

def count_chars(s):
    digits = letters = spaces = 0

    for char in s:
        if char.isdigit():
            digits += 1
        elif char.isalpha():
            letters += 1
        elif char.isspace():
            spaces += 1

    return digits, letters, spaces

s = input("Enter a string: ")
digits, letters, spaces = count_chars(s)

print("Digits: ", digits)
print("Letters: ", letters)
print("Spaces: ", spaces)

In this program, we define a function count_chars(s) that takes a string s as input. It initializes three counters digits, letters, and spaces to 0. Then it iterates over each character in the string. If the character is a digit (checked using char.isdigit()), it increments the digits counter. If the character is a letter (checked using char.isalpha()), it increments the letters counter. If the character is a space (checked using char.isspace()), it increments the spaces counter. Finally, it returns the three counters.

The main part of the program asks the user to enter a string, calls the count_chars(s) function with the entered string, and prints the returned counts of digits, letters, and spaces.

This problem has been solved

Similar Questions

Python code to calculate the number of digits in a string.Sample Input:Welc0meSample OutputThe number of digits is: 1

Write a Python program to count the number of occurrences of a specific character in a string

Write a Python program to search the numbers (0-9) of length between 1 to 3 in a given string

Read a string with words separated by space and return its length and count of consonants.Sample Inputwrite a programSample Output158

Write a python program to count the number of characters of alphabets 'O' and 'i' from the given file

1/3

Upgrade your grade with Knowee

Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.