MED MED - 3 months ago 9
Python Question

Dynamically call a var inside string in function

I'm new to python, I have var (string) which is an Xpath query. I want to pass the variable

i
into the Xpath query. A simple example below:

i = 0
self.var = 'li['+i+']'

def test(self):
while(i<10):
print self.var # 'li[0]', 'li[1]' ...
i += 1

Answer

You would need to call str on the variable i, you cannot concatenate an int and a str:

 'li['+str(i)+']'

Or just use str.format, you can also pass use range and xpath indexing is also 1-based so you would start at 1:

 self.var = "li[{}]"
 def test(self):
    for i in range(1, 11):
       print self.var.format(i)

Or if using lxml for your Xpath queries you can use an Xpath variable like below:

 .xpath("li[$i]", i=i)