I have a variable, that we'll call x
, which stores the string test
I have another variable, that we'll call y
, which stores the string value x
Is there any way that I could print(y)
, in order to return test
In other words, how can I print
the value of y
which itself stores the name of the variable x
?
I should also mention that I cannot just print(x)
, because x changes, (as does its string value).
CodePudding user response:
>>> x="test"
>>> y="x"
>>> eval(y)
'test'
But don't use eval. A better approach would be to use a mapping, such as a dictionary.
>>> mapping = {"x": "test"}
>>> mapping[y]
'test'
Actually, variables in python are in a dictionary anyway, accessible via either the globals()
or locals()
builtins. So, another way to access a name dynamically is…
>>> globals()[y]
'test'
…but this is just a more magical and less clear solution to creating the dictionary that you really need.
CodePudding user response:
You can create a dictionary:
d = {"x": "test"}
y = "x"
print(d[y])
If you want to use variable x
then you can set some value to x
as initializing. As you said x
value can change:
x = None # can be any value depending on the user.
d = {x: "test"}
y = x
print(d[y])
Output:
"test"