在 Python 中计算并显示字符串中的元音
pythonserver side programmingprogramming更新于 2026/1/22 9:16:17
给定一个字符串,让我们分析一下其中有多少个字符是元音。
使用集合
我们首先找出所有单独的和唯一的字符,然后测试它们是否存在于表示元音的字符串中。
示例
stringA = "Tutorialspoint is best"
print("Given String:\n",stringA)
vowels = "AaEeIiOoUu"
# 获取元音
res = set([each for each in stringA if each in vowels])
print("The vlowels present in the string:\n ",res)
输出
运行上述代码得到以下结果 −
Given String:
Tutorialspoint is best
The vlowels present in the string:
{'e', 'i', 'a', 'o', 'u'}
使用 fromkeys
此函数通过将字符串视为字典来提取元音。
示例
stringA = "Tutorialspoint 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:
tutorialspoint is best
The count of vlowels in the string:
{'a': 1, 'e': 1, 'i': 3, 'o': 2, 'u': 1}
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

