从文本文件读取和打印时如何防止我的程序添加不需要的空行 - Python3

How can I prevent my program from adding unwanted blank lines when reading and printing from text file - Python3

我有代码可以读取文本文件并打印文件中包含用户输入的特定单词(例如姓名)的行。

问题是,如果程序找到与 'searched word' 匹配的多行,则程序将打印这些行,并在它们之间添加一个空行。我如何让这个程序打印与搜索匹配的行,而不用空行分隔每个结果?

line_number = 0

name = input("Who are you looking for? ")

with open('example.txt', "r") as a_file:
    for a_line in a_file:
        line_number += 1
        if name in a_line:
            print(line_number, a_line)

input()

可能是一个非常简单的解决方案,但我很困惑,我们将不胜感激。

print函数中使用end参数,像这样

print(line_number, a_line, end="")

print 函数的默认参数列表如下所示,

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

由于 end\n,每次 print 调用后都会插入一个新行。

试试这个:

 line_number = 0

name = input("Who are you looking for? ")

with open('example.txt', "r") as a_file:
    for a_line in a_file:
        line_number += 1
        if name in a_line:
            input(print("{}, {}".format(line_number, a_line)))

我怀疑您得到的 "extra lines" 是使用 input() 的结果,它在所需输出的 ​​print() 之后添加了一个新行。相反,您可以只在 input() 的显示文本中使用所需的输出。

您从文本文件中读取的每一行末尾仍会有换行符,接受答案的替代方法是在打印时将其删除:

line_number = 0

name = input("Who are you looking for? ")

with open('example.txt', "r") as a_file:
    for a_line in a_file:
        line_number += 1
        if name in a_line:
            print(line_number, a_line.rstrip())

input()

如果您想更具体一些,可以改用 .rstrip("\n"),但我猜您对任何空格都不感兴趣(这是 rstrip 在没有参数的情况下所做的)。