用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}热门推荐
10 长辈生日祝福语简短女性
11 团队文案祝福语简短励志
12 给宝贝开学祝福语简短
13 参加婚礼祝福语大全简短
14 圆圆的祝福语简短
15 国庆中秋祝福语简短搞笑
16 怀念青春祝福语简短
17 写给老师祝福语简短大学
18 特别的端午祝福语简短