Python interpret input as math function [duplicate] - python

This question already has answers here:
Evaluate math equations from unsafe user input in Python
(2 answers)
Closed 4 years ago.
How do you turn a string gathered from input into an actual function? For example,
>>>function = input("Enter a function: ")
>>>Enter a function: "sin(t)"
And then I'd be able to use the entered function. Is there a library to parse through the string and return a math function like so?

You can use exec
>>> import math
>>> t=45
>>> exec('s=math.sin(t)')
>>> s
0.8509035245341184
>>>
Or if you just want the function
>>> exec('f=math.sin')
>>>
>>> f(45)
0.8509035245341184
>>>

Related

How to find the exponential of a number? [duplicate]

This question already has answers here:
How can I use "e" (Euler's number) and power operation?
(7 answers)
Closed 3 months ago.
What is the easiest/most optimal way of finding the exponential of a number, say x, in Python? i.e. how can I implement e^x?
The easiest and most optimal way to do e^x in Python is:
from math import exp
print(exp(4))
Output
>>> 54.598150033144236
You can use the math.exp() function from the math module (read the docs).
>>> import math
>>> x = 4
>>> print(math.exp(x))
54.598150033144236

F-string in Python ":.3f" [duplicate]

This question already has answers here:
Limiting floats to two decimal points
(35 answers)
how to format float number in python? [duplicate]
(3 answers)
variable number of digit in format string
(3 answers)
Closed 1 year ago.
I'm reading this textbook called "Practical Statistics for Data Scientists" and this :.3f keeps getting used in almost every f-string. What does :.3f mean? My guess is it has something to do with floating point numbers.
Example:
{house_lm_factor.intercept_:.3f}
This is show you how many number are printing:
>>> import math
>>> flt = math.pi
>>> f'{flt:.3f}'
'3.142'
>>> f'{flt:.5f}'
'3.14159'
>>> f'{flt:.10f}'
'3.1415926536'

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"

automatically convert string to appropriate type [duplicate]

This question already has answers here:
How to convert list of strings to their correct Python types?
(7 answers)
Closed 3 years ago.
I am trying to find a function to have python automatically convert a string to the "simplest" type. Some examples:
conversion_function("54") -> returns an int 54
conversion_function("6.34") -> returns a float 6.34
conversion_function("False") -> returns a boolean False
conversion_function("text") -> returns a str "text"
R has a function called type.convert that does this. What is the way to do this in python? Is there an existing function or does one need to create a custom one?
You can use ast.literal_eval, and fall back to no conversion (returning the original string) if it fails:
from ast import literal_eval
def simplest_type(s):
try:
return literal_eval(s)
except:
return s
Examples:
>>> simplest_type('54')
54
>>> simplest_type('6.34')
6.34
>>> simplest_type('False')
False
>>> simplest_type('text')
'text'
You can use ast.literal_eval.
import ast
a='[1,2,3]'
b='False'
c='1.2'
print(ast.literal_eval(a),ast.literal_eval(b),ast.literal_eval(c))
Note:
ast.literal_eval only works for valid python datatypes.

Convert String into list in python [duplicate]

This question already has answers here:
Converting JSON objects in to dictionary in python
(3 answers)
Closed 5 years ago.
I am trying to convert the following string into list. However I get the variable enclosed in round brackets.
a = '{"0": "407-1656"}, {"4": "512-873"}'
b = [a]
on executing above following is the value of b
['{"0": "407-1656"}, {"4": "512-873"}']
I require the output to be
[{"0": "407-1656"}, {"4": "512-873"}]
Thanks.
You can use ast.literal_eval()
>>> from ast import literal_eval
>>> b = literal_eval(a)
>>> b
({'0': '407-1656'}, {'4': '512-873'})

Categories