Python字符串访问 我正在帮助一个Python的朋友,我可能会和C++混淆。所以我很好奇为什么这不起作用。它的预期功能是一个Pig拉丁翻译,因此如果第一个字母“ay”是元音加在末尾,但如果第一个字母是辅音,则该字母加在末尾,然后再加上“ay”。 例子: 苹果->苹果 守望相助 对不起,我完全忘记发布代码编辑 vowel = ['a','e','i','o','u'] counter = -1 while True: text = input("Write a word to translate. If you do not want to play anymore, write exit: ") if text == "exit": break elif text[0].lower() in vowel: text = text + 'ay' print(text) elif text[0].lower() not in vowel: letter = text[0] length = len(text) - 1 for i in range(1, length): text[i-1] = text[i] text[length + 1] = letter print(text)

Python字符串访问 我正在帮助一个Python的朋友,我可能会和C++混淆。所以我很好奇为什么这不起作用。它的预期功能是一个Pig拉丁翻译,因此如果第一个字母“ay”是元音加在末尾,但如果第一个字母是辅音,则该字母加在末尾,然后再加上“ay”。 例子: 苹果->苹果 守望相助 对不起,我完全忘记发布代码编辑 vowel = ['a','e','i','o','u'] counter = -1 while True: text = input("Write a word to translate. If you do not want to play anymore, write exit: ") if text == "exit": break elif text[0].lower() in vowel: text = text + 'ay' print(text) elif text[0].lower() not in vowel: letter = text[0] length = len(text) - 1 for i in range(1, length): text[i-1] = text[i] text[length + 1] = letter print(text),python,string,character,Python,String,Character,字符串是不可变的,因此不能在特定索引处指定字符串,如text[i-1]=text[i] 相反,请使用text=text[1::][text[0]+'ay'来执行您想要的操作: vowel = ['a','e','i','o','u'] counter = -1 while True: text = input("Write a word to translate. If you do not want to play anymore, write exit: ") if text

字符串是不可变的,因此不能在特定索引处指定字符串,如text[i-1]=text[i]

相反,请使用text=text[1::][text[0]+'ay'来执行您想要的操作:

vowel = ['a','e','i','o','u']
counter = -1
while True:
    text = input("Write a word to translate. If you do not want to play anymore, write exit: ")
    if text == "exit":
        break

    elif text[0].lower() in vowel:
        text = text + 'ay'
        print(text)

    elif text[0].lower() not in vowel:
        text = text[1:] + text[0] + 'ay'
        print(text)

函数在哪里?您可以发布到目前为止的代码吗?因此辅音也从第一个字母中删除了?抱歉,忘记添加代码。您可以对文本[0]使用else。元音中不使用lower,我想。我知道这是一个选项,但有没有办法让我单独访问字符串的索引并重新分配值,就像我在原始代码中尝试的那样?@RyanMarvin如果你想以原始方式执行,您可以先将字符串强制转换为列表,如letters=strtext,以便在特定索引处为其赋值,然后使用join like.joinletters将列表转换回。