how to convert string to float in python? - python

I wrote a function that inputs a string expression and i want to split the expression and use some of the content as float. i tried writing num1 = float(temp[0])
but i got an error message saying i cant convert string to float.
How can i do that in python?
Here is the part of my code:
def calculate_from_string(expression):
temp = expression.split(" ")
num1 = float(int(temp[0]))
num2 = float(int(temp[1]))
oop = temp[2]
return calculate_mathematical_expression(num1, num2, oop)
The type of expression is string.
i tried converting it this way but it didn't work on the tester i was using because i got a message that it is an invalid expression. Does anyone know how i can do it?

It would be good if you provided a snippet of your data to us.
I don't know what you were doing but this should work (and it does for me):
str_expression = '1 57 34'
num = [float(i) for i in str_expression.split()]
you could also use a numpy array:
import numpy as np
nums = np.array(str_expression.split(), dtype=np.float)
If your expression contains some alphanumerics, you can just use regular expressions to extract the numbers.
For example:
str_expression = 'bdjsbd bdka2 23 (34 >> 4) * 2ds'
the right way to extract the numbers would be:
import re
nums = [float(i) for i in re.findall('\d+', str_expression)]

def calculate_from_string(expression):
temp = expression.split(" ")
num1 = float(temp[0])
num2 = float(temp[1])
oop = temp[2]
return calculate_mathematical_expression(num1, num2, oop)
float( int( "123.45" ) ) will raise ValueError since int expect [0-9]+ but you have . in the string, which will raise value error.
2nd point if you will call int(4.5) then it will give you 4, so be careful when using int function.
But you can use float(int(string)) if your input string doesn't contain . e.g. float(int("1234")) which will give you 1234.0

Related

Issue with implementing sympy into newtons method

I was trying to make a calculator for newtons method given a function, I've got everything down except that I keep running into an issue when I'm trying to do log of a different base or ln(x).
I'd appreciate the help!
import sympy as sp
x = sp.symbols('x')
# ask for expression and initial guess
expression = input('input function: ')
initial = float(input('input an initial guess: '))
iterate = int(input('input how many times you want it to iterate: '))
# find derivative of function
f_prime = sp.diff(expression, x)
f = sp.lambdify(x, expression, 'numpy')
df = sp.lambdify(x, f_prime, 'numpy')
# newtons method rounded to 8 decimal places
for i in (1, iterate):
i = initial - (f(initial)/df(initial))
initial = round(i, 8)
print(f'The root is {initial} after {iterate} iterations')
Everytime I put in log of a different base it would give me
TypeError: return arrays must be of ArrayType or a name error
for ln(x) it would give me
AttributeError: 'Symbol' object has no attribute 'ln'. Did you mean: 'n'?
The output of your expression = input('input function: ') is of type string. Before creating f = sp.lambdify(...) you need to convert that expression into a symbolic expression. sympify is the command you need to use:
expression = sp.sympify(input('input function: '))

How to get string and int as input in one line in Python3?

I have seen the below link for my answer but still didn't get an expected answer.
If I provide Name and Number in one line, Python should take the first value as a string and second as an integer.
a, b = [int(x) if x.isnumeric() else x for x in input().split()]
It will convert to int any part of input if possible.
s, num = input("Give str and int :\n").split()
num = int(num)
print(s, type(s))
print(num, type(num))
Output :
Give str and int :
hello 23
hello <class 'str'>
23 <class 'int'>
If you're certain to have a string and a number you can use list comprehension to get the values of both.
x = "Hello 345"
str_value = "".join([s for s in x if s.isalpha()]) # list of alpha characters and join into one string
num_value = int("".join([n for n in x if n.isdigit()])) # list of numbers converted into an int
print(str_value)
>> Hello
print(num_value)
>> 345
You can get the string and int by using regular expressions as follows:
import re
input_text = "string489234"
re_match = re.match("([^0-9]*) ?([0-9]*)", input_text)
if re_match:
input_str = re_match.group(1)
input_int = re_match.group(2)
see: https://docs.python.org/3/library/re.html

Read numbers from string into float

I need to convert some strings to float. Most of them are only numbers but some of them have letters too. The regular float() function throws an error.
a='56.78'
b='56.78 ab'
float(a) >> 56.78
float(b) >> ValueError: invalid literal for float()
One solution is to check for the presence of other characters than numbers, but I was wondering if there is some built-in or other short function which gives:
magicfloat(a) >> 56.78
magicfloat(b) >> 56.78
You can try stripping letters from your input:
from string import ascii_lowercase
b='56.78 ab'
float(b.strip(ascii_lowercase))
use a regex
import re
def magicfloat(input):
numbers = re.findall(r"[-+]?[0-9]*\.?[0-9]+", input)
# TODO: Decide what to do if you got more then one number in your string
if numbers:
return float(numbers[0])
return None
a=magicfloat('56.78')
b=magicfloat('56.78 ab')
print a
print b
output:
56.78
56.78
Short answer: No.
There is no built-in function that can accomplish this.
Longish answer: Yes:
One thing you can do is go through each character in the string to check if it is a digit or a period and work with it from there:
def magicfloat(var):
temp = list(var)
temp = [char for char in temp if char.isdigit() or char == '.']
var = "".join(temp)
return var
As such:
>>> magicfloat('56.78 ab')
'56.78'
>>> magicfloat('56.78')
'56.78'
>>> magicfloat('56.78ashdusaid')
'56.78'
>>>

Pass Variables within Python Class

I have the following class. But when trying to pass the variable x to the re.match it doesnt appear to correctly work as whatever input I put in it returns "invalid"
class validate:
def __init__(self, input_value):
self.input_value = input_value
def macaddress(self, oui):
self.oui = oui
#oui = 0, input deemed valid if it matches {OUI:DEVICE ID}.
#oui = 1, input deemed valid if it matches {OUI}.
if self.oui == 0:
x = 5
elif self.oui == 1:
x = 2
if re.match("[0-9a-fA-F]{2}([.-: ][0-9a-fA-F]{2}){x}$", self.input_value):
return "valid"
else:
return "invalid"
Should I be passing var x in some other manner ?
Thanks,
Insert x into the string this way (using string formatting):
Python <2.7:
if re.match("[0-9a-fA-F]{2}([.-: ][0-9a-fA-F]{2}){%d}$" % x, self.input_value):
However if you use the python 3 way of formatting, your regex interferes.
It can be cleaner (but slower) to use concatenation.
Without concatenation:
if re.match("[0-9a-fA-F]\{2\}([.-: ][0-9a-fA-F]\{2\}){0}$".format(x), self.input_value):
With concatenation:
if re.match("[0-9a-fA-F]{2}([.-: ][0-9a-fA-F]{2})" + x + "$", self.input_value):
Note: this fails if implicit type conversion is not possible.
If you just put {x} in the middle of your string, Python doesn't actually do anything with it unless string formatting is applied.

String reversal in Python

I have taken an integer input and tried to reverse it in Python but in vain! I changed it into a string but still I am not able to. Is there any way to reverse it ? Is there any built-in function?
I am not able to convert the integer into a list so not able to apply the reverse function.
You can use the slicing operator to reverse a string:
s = "hello, world"
s = s[::-1]
print s # prints "dlrow ,olleh"
To convert an integer to a string, reverse it, and convert it back to an integer, you can do:
x = 314159
x = int(str(x)[::-1])
print x # prints 951413
Code:
>>> n = 1234
>>> print str(n)[::-1]
4321
>>> int(''.join(reversed(str(12345))))
54321

Categories