运行代码时,如何从代码中删除\ n,

时间:2019-10-16 09:31:50

标签: python

我已经做了一个排行榜,负责我一直在做的更大的测验。我已经编写了打开文本文件的代码,并在运行时执行"\n"以在不同行上打印该文本文件中的内容。但是,运行时,它不仅显示应有的名称和分数,还显示应隐藏的换行符\n。我该如何解决? 这段代码是我遇到问题的地方:

    if score == 3:
        print("You have reached the maximum amount of points and have reached the top of the current leaderboard, congrats.")

        leaderboard = open ("leaderboard.txt","r")

        write_in_file(leaderboard, score, username)

        topscores = leaderboard.readlines()

        print(topscores)

任何帮助将不胜感激,因为此评估的时限正在迅速接近。

2 个答案:

答案 0 :(得分:0)

您可以通过{p>在print()语句本身中将结尾指定为换行符。

print(topscores, end="\n")

答案 1 :(得分:0)

如MohitC所建议的,您可以使用列表理解。在发布的代码中,您打开了文件,但没有关闭它。我建议您关闭它,或者甚至更好,以后再使用此语法:

with open("myfile", "mode") as file:
    # operations to do.

超出范围时,文件将自动关闭。

因此,使用这两个建议,可以使用以下代码:

if score == 3:
    print("You have reached the maximum amount of points and have reached the top of the current leaderboard, congrats.")

    with open("leaderbord.txt", "w+") as leaderbord:
        write_in_file(leaderboard, score, username)
        topscores = leaderboard.readlines()

    # we're out of the with open(... scope, the file is automatically closed
    topscores = [i.strip() for i in topscores] # @MohitC 's suggestion
    print(topscores)