![](/img/trans.png)
[英]Printing contents of a file with and without using readlines() method
[英]Printing from a file using readlines - new lines are doubled
我的代碼是
def print_words():
letter=input("Enter First Letter:\n")
file=open("english.txt", "r")
words=[]
for word in file.readlines():
words.append(word)
if word[0].lower()==letter.lower():
print(word)
print_words()
由於某種原因,我的輸出在每行打印之后都有一個空行。 有什么建議嗎?
file.readlines
返回一個包含所有行的數組,但是不會刪除結尾的換行符(例如['hello\\n', 'bye\\n']
)。
當您打印它們時,它將打印出嵌入的換行符以及print
本身插入的另一行。
有兩種方法可以簡單地解決此問題:
print
不要插入新行: print(word, end='')
\\n
: word = word.strip()
# Or, if you want to be extremely specific: word = word.strip('\n')
遇到此類問題時,最好的理解方法是在輸出中打印可見字符:
def print_words():
letter=input("Enter First Letter:\n")
file=open("english.txt", "r")
words=[]
for word in file.readlines():
words.append(word)
if word[0].lower()==letter.lower():
print("-", word, "-")
print_words()
這樣,輸入j
后,您已經對問題的起因有了模糊的認識:
- je suis là
-
- je sais
-
如建議的那樣,您甚至可以使用print(repr(word))
來代替輸出:
'je suis là\n'
'je sais \n'
該word
包含整行,包括行尾。 一個快速的解決方法是在不包含新行print(word, end="")
情況下進行打印。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.