Tutorialspoint
Problem
Solution
Submissions

Number of Vowels in a String

Certification: Basic Level Accuracy: 57.38% Submissions: 61 Points: 5

Write a Python program that counts the number of vowels (a, e, i, o, u) in a given string.

Example 1
  • Input: string = "Hello World"
  • Output: 3
  • Explanation:
    • Step 1: Initialize a counter variable to 0.
    • Step 2: Iterate through each character in the string.
    • Step 3: Check if each character is a vowel (a, e, i, o, u) in case-insensitive manner.
    • Step 4: The vowels in "Hello World" are 'e', 'o', 'o' (3 vowels).
    • Step 5: Return the count of vowels: 3.
Example 2
  • Input: string = "Python"
  • Output: 1
  • Explanation:
    • Step 1: Initialize a counter variable to 0.
    • Step 2: Iterate through each character in the string.
    • Step 3: Check if each character is a vowel (a, e, i, o, u) in case-insensitive manner.
    • Step 4: The only vowel in "Python" is 'o' (1 vowel).
    • Step 5: Return the count of vowels: 1.
Constraints
  • 1 ≤ len(string) ≤ 10^6
  • The string may contain uppercase and lowercase letters.
  • The string contains printable ASCII characters.
  • Time Complexity: O(n), where n is the length of the string
  • Space Complexity: O(1), as it only uses a counter
StringsAmazonSnowflakeAdobe
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

The following are the steps to count the number of vowels in a string:


  • Iterate with a loop: Use a loop to check each character and count vowels.
  • Use list comprehension: sum(1 for char in s if char.lower() in "aeiou").
  • Use regular expressions: len(re.findall(r'[aeiouAEIOU]', s)).
  • Convert to lowercase: Convert the string to lowercase for easier comparison.

The following are the steps to count the number of vowels in a given string:

  • def count_vowels(input_string): Defines a function named count_vowels that takes a string input_string as input.
  • count = 0: Initializes a variable count to 0, storing the number of vowels found.
  • vowels = "aeiouAEIOU": Creates a string of vowels containing all lowercase and uppercase vowels.
  • for char in input_string: Loops through each character (char) in the input string.
  • if char in vowels: Checks if the current character is present in the vowels string.
  • count += 1: If the character is a vowel, the count is incremented by 1.
  • return count: After the loop finishes, the function returns the final value of count, which is the total number of vowels in the string.
  • The function count_vowels is called with "Hello World", and the result is saved in result.
  • print(result): Prints the value of result to the console.

Submitted Code :