English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use dictionaries and list comprehensions to calculate the number of vowels in a string.
To understand this example, you should know the followingPython ProgrammingTopic:
# Python program to calculate the number of each vowel # Vowel string vowels = 'aeiou' ip_str = 'Hello, have you tried our tutorial section yet?' # Use the casefold method to convert all uppercase letters in the string to lowercase. ip_str = ip_str.casefold() # Use each vowel letter as the key and a dictionary with value 0 count = {}.fromkeys(vowels,0) # Count the number of vowels for char in ip_str: if char in count: count[char] += 1 print(count)
Output result
{'o': 5, 'i': 3, 'a': 2, 'e': 5, 'u': 3}
Here, we take a string stored in ip str. Using the casefold() method, we make it suitable for case-insensitive comparison. Essentially, this method returns the lowercase version of the string.
We use the dictionary method fromkeys() to construct a new dictionary, with each vowel as its key and all values equal to 0. This is the initialization of the count.
Next, we usefor looptraverse the input string.
In each iteration, we check if the character is in the dictionary key (if it is a vowel, it is True), and if it is True, we increase the value1.
# Use dictionary and list comprehension ip_str = 'Hello, have you tried our tutorial section yet?' # Make it case-insensitive for comparison ip_str = ip_str.casefold() # Count vowels count = {x:sum([1 for char in ip_str if char == x] for x in 'aeiou'} print(count)
The program'sOutputthe same as above.
Here, we willlistUnderstand nested inIn the dictionary list,To calculate vowels in a single line.
However, since we iterate over the entire input string for each vowel, the program is slower.