我正在撰寫一個相對基本的打字測驗腳本以在終端中運行。我有一個示例文本塊,它被保存為text_block.txt:
Roads go ever ever on,
Over rock and under tree,
By caves where never sun has shone,
By streams that never find the sea;
Over snow by winter sown,
And through the merry flowers of June,
Over grass and over stone,
And under mountains in the moon.
以及以下函式來讀取它:
def load_text():
with open("text_block.txt", "r") as f:
lines = []
for line in f:
lines.append(line.strip())
lines = ''.join(lines)
return lines
在終端中顯示時給出以下內容:
Roads go ever ever on,Over rock and under tree,By caves where never sun has shone,By streams that never find the sea;Over snow by winter sown,And through the merry flowers of June,Over grass and over stone,And under mountains in the moon.
我如何讓它有適當的換行符來模仿文本檔案的格式?
uj5u.com熱心網友回復:
您可以通過在所有單詞之間插入換行符來獲得所需的輸出:
a = ["abc", "deg", "II"]
b = "\n".join(a)
>>> b
'abc\ndef\nII'
>>> print(b)
abc
deg
II
但是,您可能希望在末尾添加換行符,在這種情況下,只需添加:
b = "\n"
>>> print(b)
abc
deg
II
但是您也可以改進您的代碼。您可以使用串列理解來洗掉一些額外的行(它與您的示例相同)。
with open() as f:
return "".join([for line in f])
洗掉.strip()將保留檔案中的所有內容(包括現有的換行符)。
或更短:
with open() as f:
return "".join(f.readlines())
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/358026.html
上一篇:在Python中具有像oct()這樣的精確函式的代碼
下一篇:函式內部的基本函式
