我正在尝试创建一个程序来替换句子中的单词,将其翻译成Pig Latin(老师不关心元音,只关注大写字母),我似乎无法使其正常工作。这是我编写的代码。
def PiggySentence():
sentence=str(input("Please enter the sentence you would like converted
to Pig Latin: "))
sentence.split()
caps ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for word in sentence:
if word[0] in caps:
word = word[1].upper() + word[2:] + word[0].lower() + "ay"
else:
word = word[1:] + word[0] + "ay"
sentence = " ".join(sentence)
print(sentence)
PiggySentence()
说
Traceback (most recent call last):
line 18, in <module>
PiggySentence()
line 7, in PiggySentence
word = word[1].upper() + word[2:] + word[0].lower() + "ay"
IndexError: string index out of range
答案 0 :(得分:1)
这里的问题是word[2]
超出范围,这意味着字符串不够长,无法包含第三个字符。我不确定您希望程序如何处理诸如a
之类的小单词,是要跳过它们还是只附加一个ay
或其他内容。
在循环中,设置word
不会修改原始数组。您可能需要一个输出变量,可以将翻译后的单词添加到该变量,例如:
output = []
for word in sentence:
if word[0] in caps:
output.append(word[1].upper() + word[2:] + word[0].lower() + "ay")
else:
output.append(word[1:] + word[0] + "ay")
sentence = " ".join(output)
sentence.split()
放在单独的行上并不能满足您的要求,因为它只返回每个字符处拆分的数组。您想要在每个空格处分割后存储返回值,所以您想进行sentence = sentence.split(" ")
答案 1 :(得分:0)
首先,您不应该在函数内部进行输入。 其次,您不考虑单个字母的单词。 修改您的函数以仅当长度大于1时才进行Pig Latin格式化。
这样的事情。
def PiggySentence():
sentence=str(input("Please enter the sentence you would like converted to Pig Latin: "))
sentence.split()
caps ='ABCDEFGHIJKLMNOPQRSTUVWXYZ'
for word in sentence:
if len(word) > 1:
if word[0] in caps:
word = word[1].upper() + word[2:] + word[0].lower() + "ay"
else:
word = word[1:] + word[0] + "ay"
sentence = " ".join(sentence)
print(sentence)