下面是我的代码。我在做一个小程序,寻找回文的过程。我希望程序接受用户输入,将其保存到变量中,然后检查是否有空格。如果它找到一个空间来保存它的索引,然后取出它来检查回文。出于好奇,为了进一步提高我的编程技能,我希望以后能在单词相反的时候添加空格。例如,nurses run=nurseserun backwards and forwards,但是我还想向后显示它并向后添加空格。你知道吗
word = input("Please enter a word")
storeVal = word.count(" ")
print()
newWord = word.replace(" ", "")
print(newWord)
print()
while True:
if newWord == "":
print("Sorry, but you did not enter a word")
break
elif newWord == newWord[::-1]:
#use the index storeVal and add it in the string to put a space back
print(" is a palidrone")
break
elif newWord != newWord[::-1]:
print("This is not a palidron")
break
else:
print("You have reached an error")
另外,如果你对我如何提高我的提问能力或更好的写作方法有任何建议,请告诉我。谢谢你的阅读。你知道吗
只需反转
word
,而不是重建修改后的newWord
!你知道吗另外,示例中的
storeVal
并不是存储空间的索引,而是存储输入字符串中的空间数。你知道吗根据另一个答案,只是为了显示,您可以打印
word
而不是newWord
。但是,如果您想了解如何获得空间的原始位置,以下是一些提示:word.find(" ", space_index + 1)
来调用下一个空间,其中space_index
是最后找到的空间的索引,直到您得到-1,这意味着没有更多的空间相关问题 更多 >
编程相关推荐