小编Dav*_*dez的帖子

如何在文本文件中搜索单词并用 Python 打印整行?

我有正确的代码:

with open("text.txt") as openfile:
    for line in openfile:
        for part in line.split():
            if "Hello" in part:
                print(part)
Run Code Online (Sandbox Code Playgroud)

只能在文本中找到像 hello 这样的特定单词并打印它。问题是,我希望它停止仅打印该单词并打印包含该单词的整行。我怎样才能做到这一点?

这是我现在得到的结果:

hello
hello
hello
Run Code Online (Sandbox Code Playgroud)

然而,文本文件包括:

hello, i am a code
hello, i am a coder
hello, i am a virus
Run Code Online (Sandbox Code Playgroud)

python printing python-3.x

1
推荐指数
1
解决办法
223
查看次数

标签 统计

printing ×1

python ×1

python-3.x ×1