在python中,如何使用索引将空格添加到使用整数的字符串中?

2024-05-08 20:04:15 发布

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

更多信息

下面是我的代码。我在做一个小程序,寻找回文的过程。我希望程序接受用户输入,将其保存到变量中,然后检查是否有空格。如果它找到一个空间来保存它的索引,然后取出它来检查回文。出于好奇,为了进一步提高我的编程技能,我希望以后能在单词相反的时候添加空格。例如,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")

另外,如果你对我如何提高我的提问能力或更好的写作方法有任何建议,请告诉我。谢谢你的阅读。你知道吗


Tags: andthe代码程序信息isnotword
2条回答

只需反转word,而不是重建修改后的newWord!你知道吗

print("{} is a palidrone".format(word[::-1]))

另外,示例中的storeVal并不是存储空间的索引,而是存储输入字符串中的空间数。你知道吗

根据另一个答案,只是为了显示,您可以打印word而不是newWord。但是,如果您想了解如何获得空间的原始位置,以下是一些提示:

  • word.find(" ")将为您提供第一个空间的索引,或者-1如果找不到,您可以将其保存到一个列表中,然后调用word.find(" ", space_index + 1)来调用下一个空间,其中space_index是最后找到的空间的索引,直到您得到-1,这意味着没有更多的空间
  • 另一种更受教育的方法(依我看)是枚举字符串,并使用列表理解(或set,当然不关心顺序)收集列表中空格的所有索引。你知道吗

相关问题 更多 >