-4

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

l.b.dev
  • 151
  • 3
  • 10
  • 4
    I would recommend you to use dictionaries. I believe it will be much better and comfortable for your case. Anyway, you can try something like this `exec("print(value" + str(x) + ")")` but it is awful practice. – Nikitka Feb 19 '18 at 08:15

1 Answers1

0
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.

Hou Lu
  • 3,012
  • 2
  • 16
  • 23
  • 1
    And even then, you should still not use `eval` - there _are_ better solutions. – bruno desthuilliers Feb 19 '18 at 08:29
  • such as ? @brunodesthuilliers – l.b.dev Feb 19 '18 at 08:50
  • 1
    Store these values in `list` or `dict`. – Hou Lu Feb 19 '18 at 08:52
  • @l.b.dev in this case using a dict or a list or objects and `getattr` are the canonical solutions - "dynamic" variables are a terrible idea anyway. – bruno desthuilliers Feb 19 '18 at 09:07
  • I understand it but I have 15 lines of code "if value1 <" , "if value2 <" , "if value3 <" , "if value 15... with each time 10 lines of code in it but i need to have the value1 to have the value2 and so on. but i want to compress those 150 lines of code to avoid more code duplication. Also this code will apply to something like 10 000 first value that i need to change so it can't be done with a list or a dict because it would be to complicated to name all the value in the dict @brunodesthuilliers – l.b.dev Feb 19 '18 at 09:37
  • 2
    @l.b.dev if your code is such a mess then obviously you don't have the right data structure for the task at hand. Just a hint: python functions are objects too, so you can map indices to functions quite easily (that's just a list or tuple), and `zip` values and functions. Actually we have a perfect case of XY problem here - you ask about what you think is the solution instead of asking about your _real_ problem (the one you're trying to solve with this "solution"). – bruno desthuilliers Feb 19 '18 at 10:33