Home > Back-end >  How to convert a string to a variable name in python
How to convert a string to a variable name in python

Time:06-11

I have a list of two strings:

x = ['feature1','feature2']

I need to create the following list y from the list x:

y = [feature1, feature2]

How can I do that in Python?

CodePudding user response:

One could directly put the variables into globals:

x = ['feature1','feature2']

for varname in x:
    globals()[varname] = 123

print(feature1)
# 123

This will allow creating y as specified in the question.

The fact that it's possible, however, doesn't indicate that it should be done this way. Without knowing specifics of the problem you are solving, it's difficult to advise further, but there might be a better way to achieve what you are after.

  • Related