在Python中查找单词的第一个元音

2024-04-20 01:37:51 发布

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

所以我很难找到输入字符串的第一个元音的索引。当输入“elephant”、“hello”、“spa”时,它们正常工作,但是当我输入“spam”时,它不起作用,它返回数字3而不是2。我很难找到为什么它满足else语句而不是初始if条件。我还试图设置一个条件,如果字符串中没有元音,那么它应该打印出字符串中最后一个字符的索引。以下是我的代码:

def find_first_vowel(word):
    i = 0   
    while i < len(word):
        i+= 1
        if word[i] in vowels:
            return i
        else:
            return len(word)-1
    return i

print(find_first_vowel("spam"))   

Tags: 字符串hellolenreturnifspamfind条件
3条回答

其中一个return语句立即跳出while循环,而不查看单词的其余部分。附加问题:由于您从i += 1开始,函数甚至从不查看第一个字符,即word[0]。在

我认为您的主要问题是您的意思是,如果while循环完成并退出而没有找到元音,则执行else语句。但是,由于缩进,它是while循环中if语句的一部分,并在第二个字符不是元音时执行。你想要更像这样的东西:

i = 0
while i < len(word):
    if word[i] in vowels:
        return i
    i += 1

如果这个单词没有元音,那么函数会返回什么。在

如果位置1中的字符不是元音,则代码始终返回len(word)-1。另外,elephant不起作用,spa也只是因为我提到的错误才起作用,它返回2,它是{},而不是找到的元音的索引。试着逐行调试你的代码,你会很快找到答案的。在

这可能是一个工作代码,如果没有元音,则返回-1,否则返回找到的第一个元音的索引。在

def find_first_vowel(word):
    i = 0   
    while i < len(word):
        if word[i] in vowels:
            return i
        i += 1
    return -1

编辑

如果您想返回没有元音的最后一个字符,只需将return -1改为return len(word) - 1。这里:

^{pr2}$

您应该使用^{}为您处理跟踪索引

vowels = set('aeiou')

def find_first_vowel(word):
    for index, letter in enumerate(word):
        if letter in vowels:
            return index
    return index  # Returns last index if no vowels.  You could also return None, or raise an error

相关问题 更多 >