个性化阅读
专注于IT技术分析

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

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

先决条件:Python Set用法

例子:

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

方法:

1.使用set()创建一组元音, 并将count变量初始化为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 = "srcmini" # Function Call vowel_count( str )

输出如下:

No. of vowels : 5

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python程序在给定字符串中使用集合来计算元音数

评论 抢沙发

评论前必须登录!