从文本文件读取和打印时如何防止程序添加不需要的空行-Python3 [英] How can I prevent my program from adding unwanted blank lines when reading and printing from text file - Python3

查看:54
本文介绍了从文本文件读取和打印时如何防止程序添加不需要的空行-Python3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码可以读取文本文件,并在文件中包含用户输入的特定单词(例如名称)的情况下打印文件中的行.

I have code which will read a text file and print the lines from the file if they contain a particular word entered by the user (for example a name).

问题是,如果程序找到多行与搜索到的单词"匹配的行,则程序将打印这些行,并在它们之间添加一个空行.如何使该程序打印与搜索匹配的行,而没有空白行分隔每个结果?

The issue is that if the program finds more than one line which matches the 'searched word', then the program will print the lines with an addition blank line between them. How do I get this program to print lines which match the search without a blank line separating each result?

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()

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

Probably a very simple solution but I am stumped, any help would be appreciated.

推荐答案

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

Use end parameter in print function, like this

print(line_number, a_line, end="")

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

The default list of parameters to print function looks like this,

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

由于 end 具有 \ n ,因此每次调用 print 后都会插入新行.

Since end has \n, a new line will be inserted after every print call.

这篇关于从文本文件读取和打印时如何防止程序添加不需要的空行-Python3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆