Dynamically call a var inside string in function
<p>I'm new to python, I have var (string) which is an <em>Xpath</em> query. I want to pass the variable <em><code>i</code></em> into the <em>Xpath</em> query. A simple example  below:</p>

<pre><code>i = 0
self.var = 'li['+i+']'

def test(self):
  while(i&lt;10):
   print self.var #  'li[0]', 'li[1]' ...
   i += 1
</code></pre>

<p>You would need to call <em><code>str</code></em> on the variable <em><code>i</code></em>, you cannot concatenate an int and a str:</p>

<pre><code> 'li['+str(i)+']'
</code></pre>

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

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

<p>Or if using <em>lxml</em> for your Xpath queries you can use an  <a href="http://lxml.de/xpathxslt.html" rel="nofollow">Xpath variable</a> like below:</p>

<pre><code> .xpath("li[$i]", i=i)
</code></pre>

python