0

I can not find the appropriate syntax or method to do this, which is why I am reaching out.

I am using python 2.7 lxml etree

my code is similar to this:

for y in mytree.iterfind('./level1/level2/level3/[2]'):
  print y.tag, y.text

Essentially printing all of the available tags and text in the second iteration of the level. (I know how many there are, I am not having issues with indexing or making the function work).

I am attempting to loop through them using 'i' as a defined variable (incrementally increasing 'i' to the defined number of items).

This does not work:

for y in mytree.iterfind('./level1/level2/level3/[i]'):
  print y.tag, y.text

I also tried creating the string as a variable (concatenating the text with the 'i variable as a string, but python did not recognize that it was a function anymore.

Any suggestions or help would be appreciated.

zx485
  • 28,498
  • 28
  • 50
  • 59

1 Answers1

1

You need to build the path string using the value of i, e.g (untested):

for y in mytree.iterfind('./level1/level2/level3/[%d]'%(i)):
  print y.tag, y.text

If in doubt, construct the string outside the interfind call so you can print it, e.g. (untested):

for i in range(3): # or whatever the i loop is...
    pathstr = './level1/level2/level3/[%d]'%(i)
    print pathstr
    for y in mytree.iterfind(pathstr):
        print y.tag, y.text
  • Awesome, that worked perfectly. I have to learn how that works, meaning the syntax with the %d and %I. I have experience working with macros so searching for this will work now that you pointed me in the right direction by giving me the answer. I am still very new to python. I appreciate the help! – Scientific40 Mar 31 '18 at 22:35
  • Do note: [`str.format` is preferred to the modulo operator](https://stackoverflow.com/q/5082452/1422451) which the latter is used here. – Parfait Apr 01 '18 at 01:39