用Python计算并显示字符串中的元音
给定一个字符串,让我们分析多少个字符是元音。
带套
我们首先找出所有单个和唯一字符,然后测试它们是否在表示元音的字符串中存在。
示例
stringA = "Nhooo is best"
print("Given String: \n",stringA)
vowels = "AaEeIiOoUu"
# Get vowels
res = set([each for each in stringA if each in vowels])
print("The vlowels present in the string:\n ",res)输出结果
运行上面的代码给我们以下结果-
Given String:
Nhooo is best
The vlowels present in the string:
{'e', 'i', 'a', 'o', 'u'}与fromkeys
通过将其视为字典,此功能可以从字符串中提取元音。
示例
stringA = "Nhooo is best"
#ignore cases
stringA = stringA.casefold()
vowels = "aeiou"
def vowel_count(string, vowels):
# Take dictionary key as a vowel
count = {}.fromkeys(vowels, 0)
# To count the vowels
for v in string:
if v in count:
# Increasing count for each occurence
count[v] += 1
return count
print("Given String: \n", stringA)
print ("The count of vlowels in the string:\n ",vowel_count(stringA, vowels))输出结果
运行上面的代码给我们以下结果-
Given String:
nhooo is best
The count of vlowels in the string:
{'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短