![](/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.