MBasith MBasith - 3 months ago 16
Python Question

Python print next line while printing from for loop

I am performing a for loop on a list and would like to find a match and print the next line. However, when I try to use the next() method I keep getting a failure. Can I please get some help in extracting the next line after a specified match?

string (for loop output):

item_0
0
item_1
0




item_3
727

item_4
325


For Loop to find match and next line:

result = tree.xpath('//tr/td/font/text()')

for line in result:
if 'item_3' in line:
print(line.next())


Error:

AttributeError: '_ElementStringResult' object has no attribute 'next'

Answer

line is a lxml.etree._ElementStringResult (a modified str) in your code. lxml.etree._ElementStringResults do not have a next method which is why you are getting an AttributeError.

You can set a flag indicating that the next line should be printed as follows:

print_line = False
for line in result:
    if print_line:
        print(line)
        print_line = False
    if 'item_3' in line:
        print_line = True
Comments