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

2024-06-17 11:17:34 发布

您现在位置: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)

任何帮助都将不胜感激,因为这项评估有一个很快就要到的时限。你知道吗


Tags: ofthe代码名称内容have行上score
2条回答

您可以指定end是print()语句本身中的换行符

print(topscores, end="\n")

正如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)

相关问题 更多 >