假设我有这样的文本:
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()
关于python - 如何在所选字符串上方获得两行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6244942/