MED MED - 1 month ago 5x
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

into the Xpath query. A simple example below:

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

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


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


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)