0

I am relatively new to Python, and I'm wondering how I can call a variable in the name of a new variable.

For example, when I have the 2 following variables and their values:

number1 = 100
string1 = 'abc'

and I want to write a line of code such that I can create new variables who's name contains the values of variables number1 and string1 (e.g new_var_100 and new_var_abc)

For example:

new_var_(value_of_number1) = 200   ##What to write on LHS?
new_var_(value_of_string1) = 'def'  ##What to write on LHS?

such that when I call new_var_100, it returns 200; and when I call new_var_abc, it returns 'def'.

Thanks very much.

Jason
  • 31
  • 1
  • 4
  • 5
    you don't want to do this. make a dictionary instead. – Paul H Oct 03 '19 at 13:38
  • For a number, in this case, multiply by 2. For a string, increase the "value" of each character by 3 or the length of the string, your choice. – Ṃųỻịgǻňạcểơửṩ Oct 03 '19 at 13:38
  • 1
    You should probably use a dictionary, but if you really want to do this, check out this question: https://stackoverflow.com/questions/11553721/using-a-string-variable-as-a-variable-name – rpm192 Oct 03 '19 at 13:40

2 Answers2

0

not realy sure if you shuld do this but here goes:

string1 = 'abc'

globals()[f"string1{number1}]=200```
Bendik Knapstad
  • 1,409
  • 1
  • 9
  • 18
0

You can't - at least not without involving some very hacky solutions.

If you want to treat variable names as strings, modifying or concatenating them, you actually want a dictionary:

my_dict = {'number1' = 100, 'string1' = 'abc'}

You then access those values by passing the key values inside brackets - which fundamentally work like arbitrary variable names:

my_dict['number1']  # returns 100 
my_dict['string1']  # returns 'abc'

you can then use a simple for loop to create new values based on some logic:

for value in my_dict.values():
    my_dict['new_var_' + str(value)] = 200

Note that my code simply sets the values associated with the keys 'new_var_100' and 'new_var_abc' to 200. You'll need extra logic if you want to update strings and ints differently.

jfaccioni
  • 7,099
  • 1
  • 9
  • 25