Python代码,用于查找param中的元音数

2024-09-24 02:23:48 发布

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

我是一个python新手,正在为我认为简单的代码而奋斗。我的指令是,编写一个接受一个字符串参数单词并返回字符串中元音字母数的函数。在

另外,为了澄清一下,supercat是我的一个字符串参数词。在

我花了一段时间来研究这段代码,结果有点混乱。 这就是我目前所拥有的。在

vowelletters = ["A","E","I","O","U","a","e","i","o","u"]

def isVowel(supercat):
        if supercat in vowel:
            return True
        else: 
            return False
    print isVowel(supercat)

    def countvowel(supercat):
        count = 0
        for index in super cat:
            if isVowel(vowelletters): count += 1
        return count

    y = countvowel(super cat)
    print(y)

Tags: 字符串代码in参数returnifdefcount
3条回答

在我看来,你的压痕有问题,你在那里留了一个多余的空间。(超级猫而不是超级猫)

您还在count元音()中使用了元音元音而不是索引,并且忘记在is元音()中使用global语句。在

vowelletters = ["A","E","I","O","U","a","e","i","o","u"]

def isVowel(supercat):
    global vowelletters
    if supercat in vowelletters:
        return True
    else: 
        return False
    print isVowel(supercat) # This isn't executed
            # because it is after a return statement.

def countvowel(supercat):
    count = 0
    for index in supercat:
        if isVowel(index): count += 1
    return count

y = countvowel("supercat")
print(y)

您可以先创建字符串来测试lowercase(),这样就不必检查大写元音(这样可以提高效率)。接下来,您可以count()测试字符串中每个元音的次数,并做最后一个sum()来得到总数。在

vowelletters = ["a","e","i","o","u"]

teststring= "hellO world foo bAr"

count = sum(teststring.lower().count(v) for v in vowelletters)

print count #6

您可以将所有内容放在一个函数中,以便轻松重用代码。在

^{pr2}$

变量名中不允许有空格,我想说:

for index in super cat:

以及

y = countvowel(super cat)

相关问题 更多 >