Skip to content Skip to sidebar Skip to footer

Convert String To Variable In Python?

I am very new with python and programming altogether and have been trying to figure out how to do this for a while. Here's what I need help with: y=0 x=2 p01='hello' p02='bye' pri

Solution 1:

You could use eval()...

It evaluates an expression stored in a string as if it were Python code.

In your case, 'p'+(str(y)+str(x)) becomes 'p01', so it gets the result of the expression p01, which is of course 'bye'.

print(eval('p'+(str(y)+str(x))))

Note however that you should never do this - there is almost always a better way. Please read Why is using 'eval' a bad practice?

So, what can we do?

globals() gives us a dictionary of all of the global variables in your Python program, with their name as a string index and their value as the dictionary value. Thus, we can simply do:

globals()['p'+(str(y)+str(x))]

Which evaluates to globals()['p01'], which gets the value of global p01 - which is bye.

Again, this is a workaround to a bigger problem

Restructure your code. Make them into an array or dictionary and get the index of it. Think through why you would want to do this, and change your code so that you do not have to. It is bad to be in a situation where eval looks like the best option.


Post a Comment for "Convert String To Variable In Python?"