在Python中计算字符串中元音的数目

2024-05-03 13:42:59 发布

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

好吧,我所做的是

def countvowels(st):
    result=st.count("a")+st.count("A")+st.count("e")+st.count("E")+st.count("i")+st.count("I")+st.count("o")+st.count("O")+st.count("u")+st.count("U")
    return result

这是可行的(我知道在这篇文章中缩进可能是错误的,但是我在python中对缩进的方式是有效的)。在

有更好的方法吗?使用for循环?在


Tags: 方法forreturndefcount错误方式result
3条回答

我会做一些类似的事情

def countvowels(st):
  return len ([c for c in st if c.lower() in 'aeiou'])

你可以用列表理解来实现

def countvowels(w):
    vowels= "aAiIeEoOuU"
    return len([i for i in list(w) if i in list(vowels)])

当然还有更好的方法。这里有一个。在

   def countvowels(s):
      s = s.lower()
      return sum(s.count(v) for v in "aeiou")

相关问题 更多 >