【问题标题】:to print nth line after a matched string from a text using python使用python从文本中打印匹配字符串后的第n行
【发布时间】:2021-06-29 05:26:12
【问题描述】:
我在文本下方,我想打印字符串后的第 7 行:XXXXXXXX
text = """XXXXXXXX
ABC
XYZ
Today
Yesterday
Daily Price Change
Hello
4,462
4,398"""
预期输出:
4,462
网络上的大多数答案都是使用文本文件,我正在尝试使用if "XXXXXXXX" in text: 进行检查,但无法继续进行。
非常感谢您的帮助!
【问题讨论】:
标签:
python-3.x
text-processing
【解决方案1】:
使用re 模块
import re
s='the string'
s=re.sub(r'^.*?xxxxxxxx','xxxxxxxx',s)
print(s.split("\n")[6])
【解决方案2】:
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