Python Print Variables with parameters
<p>I know you can do this for a string:</p>

<pre><code>print("You have inputted {0} postive numbers and {1} negative numbers".format('3','2'))
</code></pre>

<p>And this would produce:</p>

<pre><code>You have inputted 3 postive numbers and 2 negative numbers
</code></pre>

<p>But I want to insert a letter in a variable name. For example,</p>

<pre><code>number = 4
print(nu{}ber.format("m"))
</code></pre>

<p>And this should produce <code>4</code> Any ideas?</p>

<pre><code>print(eval('nu{}ber'.format("m")))
</code></pre>

<p>Eval evaluates the expression from string, and has access to program variables by default.</p>

<p>Or:</p>

<pre><code>print(globals()['nu{}ber'.format("m")])
</code></pre>

<p>Globals is the dictionary {'variable_name': value}.</p>

<hr>

<p>Unless you do trust the source of the string though, you should be careful. Fore example, if you have</p>

<pre><code>class Nuke:
    def destroy_everything():
        launch_nukes()

class Cucumber:
    ...

print(eval('nu{}ber'.format(string_received_from_user)))
</code></pre>

<p>And</p>

<pre><code>string_received_from_user = "ke.destroy_everything() or Cucum"
</code></pre>

<p>Than the command</p>

<pre><code>Nuke.destroy_everything() or Cucumber
</code></pre>

<p>will be executed.</p>

python output