简体   繁体   中英

how to print next line of the match string in python3 (If i give Tea , it should print next line too)

BANL16fd1c9a1:file_exceptions jjimmy$ python3 search_cofee_records.py
Please enter an item name:-Tea
Description will be :- Tea
QUANTITY will be :- 500
BANL16fd1c9a1:file_exceptions jjimmy$


BANL16fd1c9a1:file_exceptions jjimmy$ cat search_cofee_records_for.py
def main():

    infile=open('coffee.txt','r')
    search=input("Please enter an item :-")

    for line in infile:
        line=line.rstrip('\n')

        if (line==search):
            print("Description:-",line)

    infile.close()

main()

Just use a Boolean flag:

stop = False
def main():

    infile = open('coffee.txt','r')
    search = input("Please enter an item :-")

    for line in infile:
        line=line.rstrip('\n')

        if stop:
            print(line)
            break  ## or stop = False if you want to keep on checking for more matches

        if (line==search):
            print("Description:-",line)
            stop = True

    infile.close()

Essentially, I'm telling python that after the match has been found, I want to stop at the next line, which is why I use the stop flag, and then I break out of the loop to prevent every line afterwards from being print ed.

I think it

 line=line.rstrip('\n')

should be before loop and you should use range for loop

def main():

    infile=open('coffee.txt','r')
    search=input("Please enter an item :-")
    lines=line.rstrip('\n')

    for i in range(len(lines)):

       if (lines[i]==search):
           print("Description:-",line)
           print(line[i+1])

    infile.close()

main()

This should do just fine, unless you have a multi-gigabyte file that you don't want to load into the memory (most of the homeworks don't have such files =)

def main():
    search=input("Please enter an item :-")

    with open('coffee.txt') as infile :
        data = [i.strip() for i in infile.readlines()]

    for a,b in zip(data,data[1:] :
        if a == search :
            print("Description:-", a)
            print("QUANTITY will be :-", b)   # the next line

main()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM