+ 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?

29th Nov 2020, 1:54 AM
Michael Godfrey
Michael Godfrey - avatar
9 Answers
+ 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.
29th Nov 2020, 2:01 AM
inxanedev!
inxanedev! - avatar
+ 3
Have fun programming, glad I could help!
29th Nov 2020, 2:07 AM
inxanedev!
inxanedev! - avatar
+ 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...
29th Nov 2020, 2:03 AM
inxanedev!
inxanedev! - avatar
+ 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...).
29th Nov 2020, 2:03 AM
Michael Godfrey
Michael Godfrey - avatar
+ 2
Michael Godfrey yep look at my answer
29th Nov 2020, 2:04 AM
inxanedev!
inxanedev! - avatar
+ 2
Much appreciated.
29th Nov 2020, 2:06 AM
Michael Godfrey
Michael Godfrey - avatar
+ 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)
29th Nov 2020, 12:01 PM
🇧🇩 𝚂𝚊𝚋𝚋𝚒𝚛 𝙷𝚘𝚜𝚜𝚊𝚒𝚗 🇧🇩
🇧🇩 𝚂𝚊𝚋𝚋𝚒𝚛 𝙷𝚘𝚜𝚜𝚊𝚒𝚗 🇧🇩 - avatar
0
Change both string into float & add them
29th Nov 2020, 1:58 AM
Sâñtôsh
Sâñtôsh - avatar
- 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))
29th Nov 2020, 2:12 AM
BroFar
BroFar - avatar