gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:58:12 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com