首页 > 解决方案 > 如果该行中的字符串与python匹配,如何打印变量内的整行文本?

问题描述

我有一个带有一些文本行的变量,我只想用 python 打印具有该特定字符串的行,如果我是 grep 命令但使用 python,而不是,我不想保存文本在一个文件中,然后解析它并打印该行,我想在内存中执行此操作,你知道,只使用变量。

标签: pythonstringmatch

解决方案


# the string you want so search from
some_string = 'first line /n second line'

# split the string into a list divided by '/n' (enter) 
some_string = some_string.split('/n')

# print the lines that have a specific word
word = 'second'
for line in some_string:
    if word in line:
        print(line)

一个例子是这样的。您可以随意修改它,以便更好地适应您的问题


推荐阅读