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

标签 python python-3.x

所以我无法找到输入字符串的第一个元音的索引。当输入字符串 "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"))   

最佳答案

如果 1 位置上的字符不是元音,您的代码始终返回 len(word)-1。另外,elephant 不起作用,spa 起作用只是因为我提到的错误,它返回 2 ,即 len(word) -1 而不是找到的元音索引。尝试逐行调试代码,您很快就会弄清楚。

这可能是一个工作代码,如果没有元音,则返回-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 即可。这里:

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

关于python - 在Python中查找单词的第一个元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55010965/

相关文章:

Python docx Lib 居中对齐图像

python - 基于文本的游戏的多维数组

python 卡夫卡: Is there a way to block a consumer on a kafka topic till a new message is posted?

python - whereis python 和 python --version 之间的矛盾

python - 导入 pandas 工具 scatter_matrix 的问题

python - 打印 numpy 数组中所有列都满足特定条件的行?

python - 如何设置实时视频捕获的时间限制?

Python - 如何将方法作为参数传递以从另一个库调用方法

python - 我的代码抛出有关 NoneType 的错误,但应该定义它

python-3.x - Python 3 中的自定义文件类型