Search code examples
pythonstringvariablesvariable-names

how to transform a string in a variable name ? python


how can I transform a string in a variable name ? I have multiple variable value1, value2, value3 and value1 = 5 when i use

x = 1 print(str("value" + str(x)))

it return "value1" and not "5"

edit: it isn't a duplicate because i am asking how to solve my problem and not if it is good or bad to use eval(it is the link which you referred me to)

so when i use eval to change the value of the variable it doesn't work ("can't assign to function call"),

global('newValue' + str(z)) eval('newValue' + str(z)) = y + value

and if you do not recommend using eval what should you use instead ? because i have a lot of 'if value1 <' and 'if value 2 <' but i want to change it to a while


Solution

  • print(eval(str(“value” + str(x))))
    

    But must not use eval even if you know it’s completely secure. There is always a better way.