Convert string to variable in python? [duplicate] - python

This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 5 years ago.
I am very new with python and programming altogether and have been trying to figure out how to do this for a while.
Here's what I need help with:
y=0
x=2
p01='hello'
p02='bye'
print('p'+(str(y)+str(x)))
The output is of course 'p02', but how can I make the output instead the value of p02 ('bye')
Hope this makes sense and I look forward to any answers.

You could use eval()...
It evaluates an expression stored in a string as if it were Python code.
In your case, 'p'+(str(y)+str(x)) becomes 'p01', so it gets the result of the expression p01, which is of course 'bye'.
print(eval('p'+(str(y)+str(x))))
Note however that you should never do this - there is almost always a better way. Please read Why is using 'eval' a bad practice?
So, what can we do?
globals() gives us a dictionary of all of the global variables in your Python program, with their name as a string index and their value as the dictionary value. Thus, we can simply do:
globals()['p'+(str(y)+str(x))]
Which evaluates to globals()['p01'], which gets the value of global p01 - which is bye.
Again, this is a workaround to a bigger problem
Restructure your code. Make them into an array or dictionary and get the index of it. Think through why you would want to do this, and change your code so that you do not have to. It is bad to be in a situation where eval looks like the best option.

Related

How to assign two function return values to two variables and use them in the same line? [duplicate]

This question already has answers here:
Apply function to each element of a list
(4 answers)
How do I iterate through two lists in parallel?
(8 answers)
Closed 11 months ago.
Right, so this might be a rather confusing question. But in my Computer science class, we were given this optional challenge to calculate the distances a catapult has achieved after a user inputs a set of angles and speeds. But the challenge is that we have to split the problem into multiple smaller functions but each function is only allowed to have one statement per function.
I think I have a way to do it but I'm having trouble with one part.
[x = get_angles(), y = get_speeds(): 2*x[i]*y[i]/GRAVITY for i in range(len(x))]
This is part of my code for creating a list of the distances travelled. Now, this is effectively pseudo-code cause I have no clue how to make it work. Does python have anything that allows something like this to happen?
Any help would be great. Sorry for being so long-winded but thanks anyway :)
Trying to change the line of code you provided into something that works, I got this:
(lambda x, y: [2*x[i]*y[i]/GRAVITY for i in range(len(x))])(get_angles(), get_speeds())
This trick uses a lambda function to "store" the x, y values and use them in the same line.
I'm not sure this does exactly what you want, but this lambda function trick still applies.

Usage of colon and equals signs in Python [duplicate]

This question already has answers here:
What are variable annotations?
(2 answers)
Closed 2 years ago.
class PrepareTableOperator(BaseOperator):
def _load_table(self):
drop_table_query: str = ( "drop table if exists " + self.get_table() )
I'm a complete newbie to python but I do have a bit of a Java background.
What I don't get is the usage of colons in python. I've googled around, and it's used for slicing and for starting function definitions. But there's no 'def' syntax in the above, so to me this doesn't look like a function.
My question is, what is the colon in Python, is it another assignment operator for dictionary values, similar to a key value pair? Is that what it's doing here? What is it doing here, essentially?
In your code snippet, it is a type annotation. It is a relatively new feature of Python that lets you keep track of the data types, so in this case, it is declaring that drop_table_query is a string.
Type annotations are checked by IDE, but not enforced by the Python interpreter. This means that drop_table_query could actually be an int and Python itself won't complain. The type annotation is just a sort of recommendation.
What it is doing here is defining that the variable will be a string (str data type). The colon is used in while loops, for loops, if statements, and functions. The colon helps the code flow into the following indented block. A single equal sign is used to assign a value to a variable, a double equal sign is used for conditions, like if var == other_var:. There is also +=, -=, *=, and /=. Those are used to shorten things like, var = var + 1, to var += 1.

Remove brackets from list [duplicate]

This question already has answers here:
How to convert string representation of list to a list
(19 answers)
Closed 5 years ago.
I have some problems with using a list in python.
Right now, I open a .txt file with data, and read it into my python file.
However, when I put the input from the datafile into variable data and print this to check if it works or not, I see a lot of extra brackets which I don't want. Right now, it looks like:
["['sports','pizza','other']"]
and I want it to have it in a way like this:
['sports','pizza','other']
Can someone help me to get this work? Reason why I want it in a format like I mentioned above, is that I want to compare the list with another list, and that does not work in the format with the ]"]
I hope someone will help me.
Simply use eval function from Python.
>>> a = ["['sports','pizza','other']"]
>>> eval(a[0])
['sports', 'pizza', 'other']

Python Gives me empty output [duplicate]

This question already has answers here:
Running python script in terminal, nothing prints or shows up - why?
(2 answers)
Closed 2 years ago.
At first I thought PythonScriptor was the problem, but I tried print('Hello World') and the output was fine.When ever I copy and paste a code it just gives me an empty line. I am currently learning Subroutines in Python, but I completely don't get it.
def myFirstSubroutine():
for i in range(1,3):
print('This is a subroutine')
The code snippet you just showed us defined the function. To execute the function, now you need to call it.
>>> myFirstSubroutine()
This is a subroutine
This is a subroutine
Thanks CoryKramer for his right answer. You need to call the function myFirstSubroutine() to get the output.
Pay attention to that lowercase letter variable is not equal to capital letter variable in Python. That means you need to use exact the function name myFirstSubroutine().
As well as 'I copied what you gave me , it doesn't work.', it can work if you really copy it instead of spelling the 'myfirstsubroutine' by yourself.

python reassigment of variable [duplicate]

This question already has answers here:
Python objects confusion: a=b, modify b and a changes! [duplicate]
(3 answers)
Closed 8 years ago.
I'm new to python (using 2.7.6) and I'm sure this has been asked before, but I can't find an answer anywhere. I've looked at the python scoping rules and I don't understand what is happening in the following code (which converts three hex number strings to integers)
ls=['a','b','c']
d=ls
for i in range(0,len(d)):
d[i]=int(d[i],64)
print str(ls)
Why does the value of ls change along with the value of d?
I couldn't repeat this behavior with simple assignments. Thanks!
d is ls.
Not the value assigned to d equals the value assigned to ls. The two are one and the same. This is typical Python behavior, not just for lists.
A simple way to do what you want is
d = ls[:]

Categories