问题描述
我有一个带有一些文本行的变量,我只想用python打印具有特定字符串的行,如果我是grep命令却是python,又不想,我不想将文本保存到文件中,然后解析并打印该行,我想仅在使用变量的情况下在内存中执行此操作。
解决方法
# 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)
一个例子就是这样。 您可以随意修改它,使其更适合您的问题