How to interpret a string as code in Python [duplicate] - python

This question already has answers here:
Evaluating a mathematical expression in a string
(14 answers)
Closed 7 months ago.
How to make a function that can interpret a string as a code ?
var1 = 5
var2 = 10
var3 = 7
str = "(var1*var2)+var3"
result = calculate(str) # I need help to write this function
result should output 57

Use result = eval(str) instead of result = calculate(str).
Disclaimer: eval() should be used carefully since it can execute anything passed to it. More details can be found in this article.

Related

Using Iterator inside a lambda statement [duplicate]

This question already has answers here:
Lambda in a loop [duplicate]
(4 answers)
What do lambda function closures capture?
(7 answers)
Closed 2 years ago.
Why is the lambda expression only outputting the same result?
I expected to get the current value of the iterator and therefore the lambda expressions would output the numbers from 1 to 4 but that is obviously not the case.
I assume that the problem may have something to do with how the iterator is treated by the lambda expression but i could not find a answer to it yet. Thank you in advance
list = []
for i in range(5):
list.append(lambda:i)
for a in list:
print(a())
---OUTPUT---
4
4
4
4

Variable inside python format specifier [duplicate]

This question already has an answer here:
How to pad numbers with variable substitution for padding width in format or f string? [duplicate]
(1 answer)
Closed 7 months ago.
I am wondering whether I can add a variable inside the f string to specify the width of item to be printed.
For example:
print("{:>5}".format("cat"))
In the example how can I replace 5 with a variable that can change at runtime.
inside the f string
Be careful using the term "f string" -- you're talking about a format string whereas an f-string is a feature of the latest releases of Python and something different, but related:
animal = 'cat'
pad = 5
print(f"{animal:>{pad}}")
Otherwise, if you just want a format string without the f-string, then #JohnnyMopp's comment (+1) shows the correct syntax.
Here is how:
a = 5
print("{:>"f"{a}""}".format("cat"))
Output:
cat
You can also do that using str.rjust():
a = 5
print("cat".rjust(a))
Output:
cat

How can I honor parentheses in evaluating arithmetic expressions? [duplicate]

This question already has answers here:
Math operations from string [duplicate]
(8 answers)
Evaluating a mathematical expression in a string
(14 answers)
Closed 3 years ago.
I am fairly new to python/ programming in general and i am trying to write a function that will convert an equation passed in as a string to its numeric representation and do some basic calculations. I am having some trouble with the parenthesis as i am not sure how to represent them for order of operations.
Any help of tips would be greatly appreciated. Thank you!
EquationAsString ="( 2 + 3 ) * 5"
def toEquation(EquationAsString):
Equation = EquationAsString.split(' ')
#store info in list and use it like a stack, check the type etc.
answer = 25
return answer
You can use the eval method to do such a thing.
Example:
print(eval('(2+3)*5'))
Output:
25
And if you really wanted to put it in a function:
def evaluation_string(input):
print(eval(input))
Example
def evaluation_string(input):
print(eval(input))
string_equation = '(2+3)*5'
evaluation_string(string_equation)
Output:
25

Replacing integers with variables in SQL commands in python [duplicate]

This question already has answers here:
Escaping chars in Python and sqlite
(4 answers)
Closed 4 years ago.
So currently my code is this which works
result = connection.execute('SELECT * FROM PastOrders WHERE CustomerID="1";')
But as others use my programme the customer will change so how do I replace 1 with a variable like this..
cat = str(1)
result = connection.execute('SELECT * FROM PastOrders WHERE CustomerID=cat;')
However, this doesn't work so any help thanks
Have you considered breaking the SQL statement.
cat = '\"+'str(1)+'\"';
result = connection.execute('SELECT * FROM PastOrders WHERE CustomerID='+cat+';)'

String to Int in Python [duplicate]

This question already has answers here:
Why does map return a map object instead of a list in Python 3?
(4 answers)
Getting a map() to return a list in Python 3.x
(11 answers)
Closed 5 years ago.
How to Convert a string like '123' to int 1,2 and 3 so that I can perform 1+2+3. I am new to python. Can you please help me? I am not able to split the list. I don't think splitting the string will be of any use as there are no delimiters. Can you help me to understand how can this string elements be separated and treated as intergers?
x = "123"
s = 0
for a in x:
s = int(a) + s

Categories