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

标签 python

假设我有这样的文本:

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/

相关文章:

python - 如何根据值计数过滤 Pandas DataFrame?

python - 在 Python 中建模 4-D 数据(带时间戳)

python - 为什么 python os.path.isfile 似乎忽略某些文件类型?

python - 简单的 Python 脚本不起作用

python - BeautifulSoup 找不到正确解析的元素

python - 如何创建带有标志修改的 QMessageBox 的子类?

python - 寻找 : nosql (redis/mongodb) based event logging for Django

python - 我应该如何创建依赖于另一个扩展的 Flask 扩展?

python - pyparsing 匹配指定文字的任意组合

python - 如何去除 wx.Notebook 中的边框