Search code examples
python-3.xtext-processing

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


I've below text and i want to print the 7th line after the string: XXXXXXXX

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

Expected output:

4,462

Most of the answers on web is using the text file, I'm trying to check using if "XXXXXXXX" in text:, but unable to proceed further.

Many thanks in advance for the help!


Solution

  • Alternative to wasifs answer would be using pythons string.splitlines() to split a multiline string to lines, something like this would work too:

    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