使用 python 在文本中匹配的字符串后打印第 n 行

to print nth line after a matched string from a text using python

我在文本下方,我想在字符串后打印第 7 行:XXXXXXXX

text = """XXXXXXXX
ABC
XYZ
Today
Yesterday
Daily Price Change
Hello
4,462
4,398"""

预期输出:

4,462

网络上的大多数答案都使用文本文件,我正在尝试使用 if "XXXXXXXX" in text: 进行检查,但无法继续。

非常感谢您的帮助!

使用re模块

import re
s='the string'
s=re.sub(r'^.*?xxxxxxxx','xxxxxxxx',s)
print(s.split("\n")[6])

wasifs 答案的替代方法是使用 pythons string.splitlines() 将多行字符串拆分为多行,这样的方法也可以:

text = """XXXXXXXX
ABC
XYZ
Today
Yesterday
Daily Price Change
Hello
4,462
4,398"""
text = text.splitlines()
c= 0 
for elem in text:
    if elem == "XXXXXXXX":
        print (text[c+7])
    c += 1