我建议使用collections.Counter(),例如像这样:
from collections import Counter
sentence = 'I study Python programming at KAIST Center For Gifted Education'
counts = Counter(sentence)
print(counts['a'])
# 3
print(counts['A'])
# 1
print(counts['e'])
# 3
print(counts['E'])
# 1
print(counts['i'])
# 3
print(counts['I'])
# 2
print(counts['o'])
# 4
print(counts['O'])
# 0
print(counts['u'])
# 2
print(counts['U'])
# 0
如果您想独立计算元音大小写,您可以在将句子传递给 Counter() 之前调用 .lower(),例如:
from collections import Counter
sentence = 'I study Python programming at KAIST Center For Gifted Education'
counts = Counter(sentence.lower())
print(counts['a'])
# 4
print(counts['e'])
# 4
print(counts['i'])
# 5
print(counts['o'])
# 4
print(counts['u'])
# 2
编辑:
如果由于某种原因你不能使用集合库,字符串有一个count() 方法:
sentence = 'I study Python programming at KAIST Center For Gifted Education'
print(sentence.count('a'))
# 3
print(sentence.count('e'))
# 3
print(sentence.count('i'))
# 3
print(sentence.count('o'))
# 4
print(sentence.count('u'))
# 2
如果您想计算的不仅仅是元音,“手动”计算子字符串(即在您的情况下为元音)可能更有效,例如:
sentence = 'I study Python programming at KAIST Center For Gifted Education'
# Initialise counters:
vowels = {
'a': 0,
'e': 0,
'i': 0,
'o': 0,
'u': 0,
}
for char in sentence:
if char in vowels:
vowels[char] += 1
print(vowels['a'])
# 3
print(vowels['e'])
# 3
print(vowels['i'])
# 3
print(vowels['o'])
# 4
print(vowels['u'])
# 2