在 Python 中计算和显示字符串中的元音
假设给定一个字符字符串,让我们分析一下其中哪些字符是元音。
使用集合
我们首先找出所有单独而独特的字符,然后测试它们是否存在于表示元音的字符串中。
示例
stringA = "Tutorialspoint 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:
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}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP