MBasith
MBasith

Reputation: 1499

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'

Upvotes: 0

Views: 1739

Answers (2)

Craig Burgler
Craig Burgler

Reputation: 1779

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

Upvotes: 2

warvariuc
warvariuc

Reputation: 59594

Haven't tested this, but try:

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

iter_result = iter(result)
for line in iter_result:
    if 'item_3' in line:
        print(next(iter_result))

Upvotes: 1

Related Questions