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

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

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

Now build a program to take string (combination of characters and digits) as input from the user and remove all the digits from the given string.Print the result as shown in the sample test cases.Sample Test CasesTest Case 1:Expected Output:str:·Hello123WorldString·after·removing·all·digits:·HelloWorldTest Case 2:Expected Output:str:·1234567890String·after·removing·all·digits:·Test Case 3:Expected Output:str:·PythonProgrammingString·after·removing·all·digits:·PythonProgramming

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

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.