0

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?

2 Answers 2

2
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.

Sign up to request clarification or add additional context in comments.

Comments

0

Though it's not recommended, you can access your variable dynamically through globals:

>>> number = 4
>>> globals()['num' + 'ber']
4

eval works too:

>>> eval('num' + 'ber')
4

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.