Search code examples
pythonstringenumerate

python print matched string, another string at nth line again starting the loop for finding string


i have just started to learn python programming. below is output file.

SERVER-XXX:
        IPADDR
        text1
        text2
        text3
    SERVER-yyy:
        IPADDR
        text3
        text1
        text2
    SERVER-zzz:
        IPADDR
        text1
        text3
        text2
  1. I am reading line by line. firstly it will search for "Server*" and print
  2. Then within SERVER another loop will start to search for another string text3 and print and Loop breaks.
  3. then again 1st loop will search for another word matched SERVER*and so on.

i require the output as :

SERVER-XXX:
text3
SERVER-yyy:
text3
SERVER-zzz:
text3

below is the code which i have prepared

import re
f = open('dsp.txt', 'r')
for i, line in enumerate(f.readlines()):
    line=line.rstrip('\n')
    line=line.strip()
    print(i, line)
    if line.startswith("SERVER"):
        while i > 0:
            i=i+1
            print i
            if "text3" in line: # here i am not able to increment line.
                x= line[i]
                print ("%d" % line + /n + x)
                break

Solution

  • You don't need two for loops for this. You just need to change the search term when one is found. Something like this:

    look = 'SERVER'
    tooglelook = lambda x: 'SERVER' if x == 'text3' else 'text3'
    for i, line in enumerate(f.readlines()):
        if look in line:
            print line
            look = tooglelook(look)
    

    for your given sample input:

    SERVER-XXX:
            IPADDR
            text1
            text2
            text3
        SERVER-yyy:
            IPADDR
            text3
            text1
            text2
        SERVER-zzz:
            IPADDR
            text1
            text3
            text2
    

    produces this output

    SERVER-XXX:
    text3
    SERVER-yyy:
    text3
    SERVER-zzz:
    text3