123Bear Honey 123Bear Honey - 3 months ago 15
Python Question

Python Print Variables with parameters

I know you can do this for a string:

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


And this would produce:

You have inputted 3 postive numbers and 2 negative numbers


But I want to insert a letter in a variable name. For example,

number = 4
print(nu{}ber.format("m"))


And this should produce
4
Any ideas?

Answer
print(eval('nu{}ber'.format("m")))

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

Or:

print(globals()['nu{}ber'.format("m")])

Globals is the dictionary {'variable_name': value}.


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

class Nuke:
    def destroy_everything():
        launch_nukes()

class Cucumber:
    ...

print(eval('nu{}ber'.format(string_received_from_user)))

And

string_received_from_user = "ke.destroy_everything() or Cucum"

Than the command

Nuke.destroy_everything() or Cucumber

will be executed.

Comments