This question already has answers here:
Is it a good idea to dynamically create variables?
(5 answers)
Closed 5 years ago.
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
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.
Related
This question already has answers here:
Getting the name of a variable as a string
(32 answers)
Closed 1 year ago.
Consider the following code:
x,y = 0,1
for i in [x,y]:
print(i) # will print 0,1
Suppose I wanted instead to print:
x=0
y=1
I realise f-strings can be used to print the intermediate variable name:
for i in [x,y]:
print(f"{i=}") # will print i=0, i=1
However, I am interested in the actual variable name.
There are other workarounds: using eval or using zip([x,y], ['x', 'y']), but I was wondering if an alternative approach exists.
I think this achieves what you want to do -
for i in vars():
print(f'{i}={vars()[i]}')
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I have a string, which is a variable name. I have to pass that variable to another function to get proper output. I tried using backtick and other techniques. What are the other ways to do that? I am a beginner and don't have much expertise in python.
for i in range(1,65):
period_writer.writerow([i, max('test' + `i`)])
I want to pass the variable as test1, test2, ..... test64 to max() function and get the maximum value of those variables.
Thanks in advance
You are trying to do this:
test1 = something
test2 = something else
for i in range(1,2):
print('test' + str(i))
however, that won't work because strings cannot be used as variable names. You can cheat somewhat by using locals(), which creates a dictionary of local variables:
test1 = something
test2 = something else
for i in range(1,2):
print(locals()['test' + str(i)])
but what you really should be doing is putting your variables into a dictionary (or list!) in the first place.
d = {'test1': something,
'test2': something else}
for i in range(1,2):
print(d['test' + str(i)])
# or even better
tests = [something, something else]
for test in tests:
print(test)
# even better, what you're trying to do is this:
for i, test in enumerate(tests):
period_writer.writerow([i+1, max(test)])
This makes it much clearer that the variables belong together and will run faster to boot.
This question already has answers here:
What is getattr() exactly and how do I use it?
(14 answers)
How can I select a variable by (string) name?
(5 answers)
Closed 6 years ago.
I need to check variables looking like this:
if name1 != "":
(do something)
Where the number right after "name" is incremented between 1 and 10.
Do I need to write the test ten times or is there a way (without using an array or a dict) to "concatenate", so to speak, variable names?
I'm thinking about something like this:
for i in range(10):
if "name" + str(i) != "":
(do something)
Edit: I can't use a list because I'm actually trying to parse results from a Flask WTF form, where results are retrieved like this:
print(form.name1.data)
print(form.name2.data)
print(form.name3.data)
etc.
Use a list, such as:
names = ['bob', 'alice', 'john']
And then iterate on the list:
for n in names:
if n != "":
(do something)
or you could have a compounded if statement:
if (name1 != "" or name2 != "" or name3 != "")
The best solution would be to use solution #1.
If you cannot use a list or a dict, you could use eval
for i in range(10):
if eval("name" + str(i)) != "":
(do something)
First of all, your app have invalid logic. You should use list, dict or your custom obj.
You can get all variable in globals. Globals is a dict.
You can do next:
for i in range(10):
if globals().get('name%d' % i):
# do something
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 years ago.
I recently looked up this topic but dint find a satisfying answer. Everybody said using dictionaries is the best way , but I don’t know how to apply that in this case:
I want a function that generates me a list of objects generated by a class.
So in pseudo-code something like :
for a in range(100):
tmp = "object" + str(a)
var(tmp) = someclass()
list add tmp
Edit , because of being marked as an duplicate.
I don’t want an answer how dictionary work , I know that. I want to know , how I can make entries which consists of an entry-name and the generated objects for that name.
I need a dictionary which looks something like:
{"1" : obj1 , "2" : obj2, "3" : obj3 ... }
Edit two:
I ended up using a list instead of a dictionary which is massively easier:
for tmp in range(100):
tmpobj = objclass()
list.append(tmpobj)
thanks for help ;)
You can use a dictionary comprehension :
{ var("object" + str(a)) : someclass() for a in range(100) }
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 8 years ago.
x=1
code(x)=5
print(code1)
I want this to work andit print "5" could anybody help me do this in python.
myList=[1,2,3,4,5,6]
print myList[2]
will print 3. You can assign an index to a variable and do this:
index=2
print myList[index]
will print 3.
You can use "code" as a list.
x=1
code=[0,0]
code[x]=5
print(code[1])
or as a dict:
x=1
code={}
code[x]=5
print(code[1])
depends on how you will use "code".
As the other answer suggested, you'll better use dictionary or a list for this.
But for your question you could it like this:
x = 1
exec(('code' + x) + '=5')
print code1
code1 will be 5.
code=[0,0]
x=1
code[x]=5
print(code[1])