计算元音的Python代码

2024-05-15 15:03:51 发布

您现在位置:Python中文网/ 问答频道 /正文

假设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)

有人能告诉我是怎么回事吗?


Tags: orof字符串in程序numberforcount
3条回答

首先,请尝试以下操作:

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

使用你自己的循环。

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))

有几个问题。首先,你分配给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:依次将iterable y中的每个项分配给名称x,因此以前分配给x的任何内容都无法再通过该名称访问。

我想你想要的是:

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

相关问题 更多 >