📌  相关文章
📜  Python程序使用给定字符串中的集合来计算元音的数量

📅  最后修改于: 2022-05-13 01:54:47.141000             🧑  作者: Mango

Python程序使用给定字符串中的集合来计算元音的数量

给定一个字符串,使用 Sets 计算给定字符串中存在的元音数。

先决条件: Python中的集合

例子:

Input : GeeksforGeeks
Output : No. of vowels : 5

Input : Hello World
Output : No. of vowels :  3

方法:
1. 使用 set() 创建一组元音并将一个计数变量初始化为 0。
2. 遍历字符串字符串的字母是否存在于集合元音中。
3. 如果存在,则增加元音计数。

以下是上述方法的实现:

# Python3 code to count vowel in 
# a string using set
  
# Function to count vowel
def vowel_count(str):
      
    # Initializing count variable to 0
    count = 0
      
    # Creating a set of vowels
    vowel = set("aeiouAEIOU")
      
    # Loop to traverse the alphabet
    # in the given string
    for alphabet in str:
      
        # If alphabet is present
        # in set vowel
        if alphabet in vowel:
            count = count + 1
      
    print("No. of vowels :", count)
      
# Driver code 
str = "GeeksforGeeks"
  
# Function Call
vowel_count(str)

输出:

No. of vowels : 5