-1

I wonder if there is a way to create variables automatically using strings, e.g. I have the following code (which does not work properly in Python):

def function(lst1, string1):
    lst2 = 'processed_' + string1
    lst2 = [] #here I created a string called lst2, but I want to use the string as the variable name.
    for i in range(len(lst1)):
        if abs(lst1[i]) >= 0.0001 :
            lst2.append(i)
    return lst2


function(list1, 'price')  # list1 is a list which contains the index for column numbers, e.g., [1,2,3]
function(list1, 'promotion')
function(list1, 'calendar')

I would expect that with the function I would be able to create lists such as processed_price, processed_promotion, and processed_calendar, and the function will return these lists.

However the code above would not work as in Python. I wonder how should I write the code properly to achieve the same goal?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Tao
  • 31
  • 1
  • 2
  • 6

1 Answers1

-1
getattr(object, name, [default])
setattr(object, name, value)

To get or set values for a variable named via a string, use one of the above as appropriate. However, any time you use user input, it can be a source of injection attacks — the user could use a name that you did not expect them to use but the name is valid so the user gets access to data they should not have access to.

So it is usually advisable to use the user input as a key into a dictionary you define.

dictionary = {
  'apple': 'my_value'
}

dictionary[user_input] = 'their_value'
Ali Samji
  • 479
  • 2
  • 7