Skip to main content
 首页 » 编程设计

python之如何在所选字符串上方获得两行

2025年05月04日20over140

假设我有这样的文本:

www.something.com 
 
get the 2 above 
 
www.somethingss.com 
 
get the 2 above 
 
www.somethingssss.com 
 
get the 2 above 

也许是这样的:

for a in text: 
    if 'get the 2 above' in a: 
        get 2 above  

我该怎么做?

请您参考如下方法:

假设上面是一个字符串:

s = '''www.something.com 
 
get the 2 above 
 
www.somethingss.com 
 
get the 2 above 
 
www.somethingssss.com 
 
get the 2 above''' 
 
s = s.splitlines() 
for i, line in enumerate(s): 
    if 'get the 2 above' in line: 
        print s[i-1], s[i-2] 

s.splitlines() 移除换行符;如果您想保留它们,请传递 True,如 s.splitlines(True)(感谢 Sven Marnach)。

要从文件中获取行列表,您可以这样做:

with open('myfile.txt', 'r') as f: 
    s = f.readlines()