【问题标题】:Printing a single line from a file and removing the extra line at the end从文件中打印单行并在末尾删除多余的行
【发布时间】:2021-06-13 03:34:37
【问题描述】:

我正在尝试制作一个脚本来告诉用户他们在游戏中的中断位置(例如:阁楼、地下室等)。问题是我试图让所有这些都打印在同一行,但句子末尾的句点打印在不同的行上。

这里是代码

f = open(cd+"/Data/currentGame", "r")
l = open(cd+"/Data/currentLocation", "r")

current_game = f.read()
current_location_lines = l.readlines()
current_location = current_location_lines[0]

f.close()
l.close()

print("You have an existing game where you left off in "+str(current_location)+".")

问题是它输出了这个:

You have an existing game where you left off in the attic
.

(句号在不同的行。)

【问题讨论】:

    标签: python python-3.x printing


    【解决方案1】:

    这是因为您阅读的行后面总是跟一个\n 字符。你需要删除它。因此,只需用此替换代码的最后一部分。 .strip() 会为你做的。 str(current_location).strip("\n")

    每当您从文本文件中读取一行时,它都会添加一个\n 字符以告知新行从那里开始。您需要在打印时将其删除,否则它会与您当前的语句混淆

    你的正确说法是

    print("You have an existing game where you left off in "+str(current_location).strip("\n")+".")
    

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 2011-03-26
      • 2012-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 2013-04-28
      • 2017-08-09
      • 1970-01-01
      相关资源
      最近更新 更多