在 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