Python2使用变量代替数字来获取字符串中的字母

2024-09-28 04:21:50 发布

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

我为自己的解决方案寻找解决方案,但要么找不到,要么就是找不到。我对编码相当陌生。我正在做一个猪拉丁语翻译与一个额外的功能,它可以从猪拉丁语翻译。我的translate TO工作得很好,但是当从第19行翻译时,我得到了一个名为“IndexError:string index out-out-range”的错误,即“end=word[length]”的位置。现在,我需要知道在Python中使用变量来替换整数是不行的,还是在我的代码中有其他问题。(请注意,我确实有一些代码,以确保我的变量是一个整数。)

print "Welcome to pig-latin translater!"
word = raw_input("What word do you want to translate?")
continue1 = False
while continue1 == False:
    tofrom = str(raw_input("Do you want to translate to or from pig-latin?"))
    tofrom = tofrom.lower()
    if tofrom == "to":
        length = len(word)
        start = word[0]
        end = word[1:length]
        translation = end + start
        word = str.title(word)
        translation = translation.lower()
        print "%s in pig-latin is %s." % (word, translation)
        continue1 = True
    elif tofrom == "from":
        length = len(word)
        length = int(length)
        end = word[length]
        length = length - 1
        start = word[0:length]
        translation = end + start
        word = str.title(word)
        translation = translation.lower()
        print "%s is %s in English." % (word, translation)
        continue1 = True
    else:
        print "Please answer to or from."
end = raw_input("Press enter to exit.")

Tags: toinputrawtranslationstartlengthtranslateword
2条回答

现在是时候学习一些为Python序列编制索引的基本知识了。在

首先,正如前面的答案所指出的,序列从索引0开始;最后一个元素在索引len-1处。在

也可以从另一端用负数索引:最后一个元素是-1,倒数第二个元素是-2,依此类推。在

在获取切片时,可以省略起始索引0或结束索引-1。在

我想你知道这行不通。。。然而。移动单个字符不是猪拉丁语的正确转换。然而,这是增量编程的一个很好的例子:一次做一到两个小的添加,测试这些,然后继续。我建议你下一步做你的外部流控制:使这个循环adlib,这样你就可以测试多个输入,而不必为每个单词重新启动程序。在

elif tofrom == "from":
    end = word[-1]
    start = word[:-1]
    translation = end + start
    word = str.title(word)
    translation = translation.lower()
    print "%s is %s in English." % (word, translation)
    continue1 = True

你的问题我不太明白。但我相信您忘了迭代列表是从0开始的。
所以如果你想访问字符串的最后一个位置,你应该从它的长度中减去1。在

word = "ABC def"
length = len(word)  # 7
end = word[length - 1]  # because there is no 7th element, only 0123456

你可以在这里改进:

^{pr2}$

而且,你不需要知道绳子的长度。可以使用如下表达式:

end = word[1:]  # means from 1st element to the end

相关问题 更多 >

    热门问题