python: convert string into variable name [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
here is my python code:
>>> listName = 'abc'
>>> exec(listName+"=[]")
>>> print listName
>>> 'abc'
excepted output:
>>> print listName
>>> []
I want to define a new variable based on that string.

Even though that may be possible for global (and not local) variables, the better, cleaner, simpler, safer, saner (all in one word: pythonic) way is to use a dictionary for dynamic names:
values = {}
varname = get_dynamic_name()
# set
values[varname] = value
# get
values[varname]

Related

Way to dynamically create new variables based on length of list in Python? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 months ago.
Is there any way that I can automatically create new variables based on how many items I have in a Python list?
For instance, if I have a variable like this:
var = (json.loads(requests.get(list[0])).text)
Is it possible to automatically create additional variables like this, depending on the length of my list? I'd like to avoid manually writing out all my variables. Let's say my list has 4 items (length = 4).
var = (json.loads(requests.get(list[0])).text)
var1 = (json.loads(requests.get(list[1])).text)
var2 = (json.loads(requests.get(list[2])).text)
var3 = (json.loads(requests.get(list[3])).text)
I would appreciate any help. Thank you.
Why don't you try to use a dict to handle this problem?
vars = {f'var{i}': json.loads(requests.get(yourlist[i])).text for i in range(len(yourlist))}
You can access your variables: vars['var1'] or vars.get('var1')
In general, creating new variables during the program execution isn't a good ideia.
The direct answer to your question is to add the values in the global dictionary. It can be done with globals, eval, exec. I don't recommend to do that because if you have a long list which change size then you have to remember how many elements you have.
Here an abstraction of the problem:
var_str_pattern = 'var{}'
val = ['smt', 'else']
for i, v in enumerate(val, start=1):
globals()[var_str_pattern.format(i)] = v
print(var1)
#smt
print(var2)
#else
For the specific question:
n = 3
var_str_pattern = 'var'
for i in range(1, n+1):
globals()[f'{var_str_pattern}{i}'] = json.loads(requests.get(list[i])).text
print(var1)
print(var2)
print(var3)
You should use a dictionary approach as in the answer of Riqq.

Replace word in string using f-string [duplicate]

This question already has answers here:
How to postpone/defer the evaluation of f-strings?
(14 answers)
Closed 2 years ago.
In Python, I'm trying to insert a variable into an imported string that already contains the variable name - as pythonically as possible.
Import:
x = "this is {replace}`s mess"
Goal:
y = add_name("Ben", x)
Is there a way to use f-string and lambda to accomplish this? Or do I need to write a function?
Better option to achieve this will be using str.format as:
>>> x = "this is {replace}`s mess"
>>> x.format(replace="Ben")
'this is Ben`s mess'
However if it is must for you to use f-string, then:
Declare "Ben" to variable named replace, and
Declare x with f-string syntax
Note: Step 1 must be before Step 2 in order to make it work. For example:
>>> replace = "Ben"
>>> x = f"this is {replace}`s mess"
# ^ for making it f-string
>>> x
'this is Ben`s mess' # {replace} is replaced with "Ben"

How to get the value of a variable by executing a string? [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have the following code:
a=2
string="a"
b=exec(string)
print(b)
Output:
None
I want b to have the value of 'a' i.e. 2 how can I do that?
If I understand your case correctly, you want to evaluate some python source from string in context of existing variables.
Builtin eval function could be used for that.
a=2
string="a"
b=eval(string)
print(b)
Anyway. Why do you need that? There is better way to do that for sure.
Probably in your case you could use dictionary to remember values instead of separate variables. And after reading "names" from file use this names as dictionary keys.
your_dict = {}
your_dict["a"] = 2
string = "a"
b = your_dict[string]
print(b)
a=2
string="b=a"
exec(string)
print(b)
exec() just exectues the code in the given string, so the assignment must be done in the string itself.

Python: Getting variable name out of List within For loop [duplicate]

This question already has answers here:
How do I create variable variables?
(17 answers)
Convert string to variable name in python [duplicate]
(3 answers)
Closed 5 years ago.
How to get a variable name out of a List within a for loop.
example:
List = ['a','b','c','d']
for i in List:
var_i_ = something
so for each letter in list there should be a new variable name like:
var_a_ = something
var_b_ = something
var_c_ = something
var_d_ = something
So i could call use it in pandas as well
List = ['a','b','c','d']
for i in List:
df_i_ = something
df_a_ = something
df_b_ = something
df_c_ = something
df_d_ = something
each needs to be a different dataframe.
I need it as a search function to save data as csv or something else.

New string after concatenation refers to an existing object [duplicate]

This question already has answers here:
Why variables holding same value has the common ID in Python? [duplicate]
(1 answer)
About the changing id of an immutable string
(5 answers)
Closed 5 years ago.
Here's my snippet of code
>>> a = "some_string"
140420665652016
>>> id(a)
>>> id("some" + "_" + "string")
140420665652016
Notice that both the ids are same. But this does not happen with integers (which are also immutable like strings).
>>> a = 999
>>> id(a)
140420666022800
>>> id(999)
140420666021200
>>> id(998 + 1)
140420666023504
I'm not able to find a reason of why it's happening only with strings.

Categories