Knowee
Questions
Features
Study Tools

Write a program to accept a string as input and print the number of consonants in the string.Input:StringOutput:IntegerConstraints1<=length of string <=1000

Question

Write a program to accept a string as input and print the number of consonants in the string.

Input: String
Output: Integer
Constraints:
1 <= length of string <= 1000

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

Solution

Sure, here is a Python program that accepts a string as input and prints the number of consonants in the string.

# Function to count the number of consonants in a string
def count_consonants(string):
    consonants = 0
    for i in range(len(string)):
        if string[i].isalpha(): # check if character is an alphabet
            if string[i] not in 'aeiouAEIOU': # check if alphabet is a consonant
                consonants += 1
    return consonants

# Accept string as input
string = input("Enter a string: ")

# Ensure string length is within constraints
if 1 <= len(string) <= 1000:
    print(count_consonants(string))
else:
    print("String length must be between 1 and 1000")

This program works by iterating over each character in the input string. If the character is an alphabet and it is not a vowel (i.e., it is a consonant), it increments the consonants counter. Finally, it prints the number of consonants in the string.

This problem has been solved

Similar Questions

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

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

Write a java program to accept a String and the perform the following operations:a) Count the number of words with the first and the last letter being same.

Write a program to count number of words in a given string whose length is greater than 3.For example:Input Resultpython is easier than C3

Define a class to accept a string and convert it into uppercase. Count and display thenumber of vowels in it.

1/2

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.