Python跳过我的if语句

时间:2013-08-13 02:41:25

标签: python if-statement output

出于某种原因,此代码不起作用:

def pyglatin(word):
    output = ""
    wordlenedit = len(word)-1
    wordlen = len(word)
    fixer = 0
    while fixer == 0:
        for i in word:
            if i == 'a' or i == 'e' or i == 'o' or i == 'i' or i == 'u':
                fixer = 1
            else:
                wordlenedit -= 1
    else:
        output = word[wordlenedit:wordlen:1] + '-' + word[0:wordlenedit:1] + 'ay'
        return output

要查看问题,请点击here。问题似乎是它正在跳过识别元音的 if 语句,但我不确定原因。这导致一些非常奇怪的输出。

2 个答案:

答案 0 :(得分:2)

你的功能不起作用,因为你从wordlenedit = len(word)-1开始,逐字逐句地减少你遇到的每个辅音的分裂指数。

for循环结束时,wordlenedit等于(length of the word) - 1 - (number of consonants)。该函数仅在单词中的第一个元音索引(从0开始)等于元音的数量时才有效。

此外,当您遍历while循环中的整个单词时,for循环在此处无用。更糟糕的是:while循环将是一个无限循环,如果你有一个没有元音的单词(如“fly”,因为你没有检查“y”)

这是您的功能的更正版本,使用关键字break

def pyglatin2(word):
    output = ""
    wordlenedit = 0
    wordlen = len(word)
    for l in word:
        if l == 'a' or l == 'e' or l == 'o' or l == 'i' or l == 'u':
            break
        else:
            wordlenedit += 1

    output = word[wordlenedit:wordlen:1] + '-' + word[0:wordlenedit:1] + 'ay'
    return output

然而,使用Regular Expressions可以用更简洁/更简单的方式编写此函数,如下所示:

import re
def pyglatin3(word):
    # Get the first index of one of these: a, e, i, o, u
    start = re.search("[aeiou]", word).start()

    # Split the word
    return word[start:] + "-" + word[0:start] + "ay"

答案 1 :(得分:0)

如果您想在不使用正则表达式的情况下执行此操作,最简单的方法是使用enumerate

def pyglatin(word):
    for i, ch in enumerate(word):
        if ch in 'aeiou':
            return word[i:] + '-' + word[:i] + 'ay'