[英]How do I remove the \n from my code when I run it,
我已經為我一直在做的一個更大的測驗制作了一個排行榜。 我編寫了打開文本文件的代碼,並在運行時執行"\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)
任何幫助將不勝感激,因為此評估的時間限制很快就會到來。
您可以指定結尾是print()
語句本身中的換行符
print(topscores, end="\n")
正如 MohitC 建議的那樣,您可以使用列表理解。 在您發布的代碼中,您打開了文件,但沒有關閉它。 我建議你關閉它,或者更好的是,將來使用這個語法:
with open("myfile", "mode") as file:
# operations to do.
當您離開 scope 時,該文件會自動關閉。
因此,使用這 2 個建議,您可以使用以下代碼:
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.