Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中查找单词的第一个元音_Python_Python 3.x - Fatal编程技术网

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

在Python中查找单词的第一个元音,python,python-3.x,Python,Python 3.x,所以我很难找到输入字符串的第一个元音的索引。当输入字符串“大象”、“你好”、“spa”时,它们工作正常,但是当我输入“垃圾邮件”时,它不工作,它返回数字3而不是2。我很难找到为什么它满足else语句而不是初始if条件。我还试图设置一个条件,如果字符串中没有元音,那么它应该打印出字符串中最后一个字符的索引。下面是我的代码: def find_first_vowel(word): i = 0 while i < len(word): i+= 1

所以我很难找到输入字符串的第一个元音的索引。当输入字符串“大象”、“你好”、“spa”时,它们工作正常,但是当我输入“垃圾邮件”时,它不工作,它返回数字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"))   
def find_first_元音(单词):
i=0
而我
如果位置
1
中的字符不是元音,则代码始终返回
len(word)-1
。另外,
elephant
不起作用,
spa
只因为我提到的bug而起作用,它返回
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
您应该使用来处理对索引的跟踪

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

无论是
return
语句还是
语句,都会立即跳出
循环,而不会查看单词的其余部分。另外一个问题:由于从
i+=1
开始,函数甚至从不查看第一个字符,即
word[0]

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

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

然后,如果单词没有元音,你希望函数返回什么。

如果元音是第一个字母,会发生什么情况,你不总是会返回1这个作品吗?但是我试图设置一个条件,如果输入的单词没有元音,然后它应该只打印最后一个字符的索引只需在我的代码中编辑
return-1
return len(word)-1
,但请注意,您将得到与最后一个字符中有元音相同的结果。
i = 0
while i < len(word):
    if word[i] in vowels:
        return i
    i += 1