Python代码统计元音字母

-1 投票
21 回答
72758 浏览
提问于 2025-04-18 10:44

假设 s 是一个由小写字母组成的字符串。

写一个程序来计算字符串 s 中包含的元音字母的数量。有效的元音字母有: 'a''e''i''o''u'。比如,如果 s = 'azcbobobegghakl',你的程序应该输出:

元音字母的数量: 5

我现在有这个代码:

count = 0
vowels = 'a' or 'e' or 'i' or 'o' or 'u'
    for vowels in s:
        count +=1
print ('Number of vowels: ' + count)

有没有人能告诉我哪里出错了?

21 个回答

1

这里是一个简单的例子:

count = 0    #initialize the count variable

def count_vowel(word):    #define a function for counting the vowels
    vowels = 'aeiouAEIOU'    #A string containing all the vowels
    for i in range(word):    #traverse the string
        if i in vowels:    #check if the the character is contained in the vowel string
            count = count + 1    #update the count
return count
2
x = len(s)        
a = 0        
c = 0        
while (a < x):        
    if s[a] == 'a' or s[a] == 'e' or s[a] == 'i' or s[a] == 'o' or s[a] == 'u':        
        c += 1        
    a = a+1        
print "Number of vowels: " + str(c)

上面的代码是给初学者用的

7

使用你自己的循环。

count = 0
vowels = ['a' , 'e' , 'i' ,'o' , 'u']
for char in s:
    if char in vowels: # check if each char in your string is in your list of vowels
        count += 1
print ('Number of vowels: ' + str(count)) # count is an integer so you need to cast it as a str

你也可以使用字符串格式化:

print ('Number of vowels: {} '.format(count))
9

作为一个开始,可以试试这个:

In [9]: V = ['a','e','i','o','u']

In [10]: s = 'azcbobobegghakl'

In [11]: sum([1 for i in s if i in V])
Out[11]: 5
10

有几个问题。首先,你对 vowels 的赋值并没有达到你想要的效果:

>>> vowels = 'a' or 'e' or 'i' or 'o' or 'u'
>>> vowels
'a'

在Python中,or 是懒惰求值的;只要有任何一个条件返回 True,它就会立刻返回结果。非空的序列,包括除了 "" 之外的字符串,都会被认为是 True,所以 'a' 会立刻被返回。

其次,当你遍历 s 时,你反正也忽略了这个赋值:

>>> for vowels in "foo":
    print(vowels)


f
o
o

for x in y: 会把可迭代对象 y 中的每一个项目依次赋值给名字 x,所以之前赋给 x 的任何值就不能再通过这个名字访问了。

我想你想要的是:

count = 0
vowels = set("aeiou")
for letter in s:
    if letter in vowels:
        count += 1

撰写回答