gpt4 book ai didi

python - 初学者问题;字符串索引超出范围

转载 作者:行者123 更新时间:2023-11-28 20:41:54 26 4
gpt4 key购买 nike

# word reverser
#user input word is printed backwards

word = input("please type a word")

#letters are to be added to "reverse" creating a new string each time
reverse = ""

#the index of the letter of the final letter of "word" the users' input
#use this to "steal" a letter each time
#index is the length of the word - 1 to give a valid index number
index = len(word) - 1

#steals a letter until word is empty, adding each letter to "reverse" each time (in reverse)
while word:
reverse += word[index]
word = word[:index]
print(reverse)

print(reverse)
input("press enter to exit")

致力于制作一个简单的程序,将用户输入的单词倒过来拼写,并通过“窃取”原始字母并从中生成新字符串将其打印回给他们。我遇到的问题是这段代码在反向 += 单词[索引]帮助或实现相同结果的更好方法非常感谢。

最佳答案

在 python 中反转单词比这更简单:

reversed = forward[::-1]

我不会使用循环,它更长而且可读性差。

关于python - 初学者问题;字符串索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31886524/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com