+ 1
Converting Strings to Floats and Integers
Is there any way to convert input strings to float or int types? Example... f = input("Enter a function: ") # f = 'x + 2' x = float(input("Enter the value of x: ") # x = 3 f = f.replace('x', str(x)) # f = '3 + 2' Is there any way to alter f so that it would output 5 as a float or int?
9 Respuestas
+ 3
At the end in the variable f you have an expression, not a number. In order to evaluate that expression, or kinda "do the math" that's in that string, you have 2 options.
1. eval function. That function takes in any python expression and simply gives you the result. However, this function is very dangerous and you should only use it when the string you pass to it is from a trusted source, which it isn't in this case. Although it's fine here I guess. Please read about the dangers of eval online.
2. A math evaluator library. If you want to avoid eval you should use some library to evaluate mathematical expressions. It might be overkill for this small of a program though, so just use eval I guess.
+ 3
Have fun programming, glad I could help!
+ 2
Såñtösh that's not practical in this case as the function the user inputs isn't always the same so you're just gonna end up writing a math expression evaluator library...
+ 2
I can see how converting the '2' and '3' characters to floats and just adding them to produce 5 would work, but I'm hoping to use f = input() part to take in more complex functions (1/x + 45, sin(x), etc...).
+ 2
Michael Godfrey yep look at my answer
+ 2
Much appreciated.
+ 1
You can convert string to int or float by int() and float() function.
#Example
string_float = "14.93"
string_int = "14"
int_number = int(string_int)
float_number = float(string_float)
print("Integer :",int_number,"\n","Float Number :",float_number)
0
Change both string into float & add them
- 1
s = str(input())
y = type(s)
f = float(s)
print(type(f),f)
x = int(input())
a = type(x)
z = float(x)
b = type(z)
print(b,z)
s = f + z
print(round(s))