To perform mathematical calculations like multiplication and division, we must explicitly parse the data from string to float or integer.
x = input('Enter value: ') print(type(x))
See the output.
Enter value: 5 <class 'str'>
You can see that even if we have entered an integer, the data type here is String. So, we have to convert it to a respected data type; otherwise, it will break the program and throw ValueError.
Python string to float
To convert string to float in Python, use the float() function. Python float() is a built-in function that converts a string to float. The float() function internally calls specified object __float__() function.
Implicit mixing floats/ints might lead to subtle bugs due to possible loss of precision when working with floats or to different results for / operator on floats/ints. Depending on the context, it might be preferable to return either int or Float, not both.
x = input('Enter value: ') print(type(x)) floatVal = float(x) print('Float Value =', floatVal) print(type(floatVal))
Output
Enter value: 6 <class 'str'> Float Value = 6.0 <class 'float'>
Example 2
stringData = '21.19114618' floatVal = float(stringData) print('Float Value =', floatVal) print(type(floatVal))
Output
Float Value = 21.19114618 <class 'float'>
How to check if an item is convertible to float
To get the input from the user in the terminal and the integer value is entered, and then you check the type of the value using the type() function, it returns String.
That means, by default, the return of input() value’s data type is String.
To check if an element is convertible, define a custom function.
pton = '1.1' qton = 11 zton = False xyz = 'Wubba Lubba Dub Dub' def is_convertible_to_float(value): try: float(value) return True except: return False print(is_convertible_to_float(pton)) print(is_convertible_to_float(qton)) print(is_convertible_to_float(zton)) print(is_convertible_to_float(xyz))
Output
True True True False
The three cases can be convertible to float, but the character string can not be converted to Float. That is why the last return False because Python can not convert a character string to Float.
Python ast.literal_eval()
The ast.literal_eval() function safely evaluates strings containing Python expressions from untrusted sources without the need to parse the values themselves.
See the following code.
import ast pton = '1.1' print(ast.literal_eval(pton))
Output
python3 app.py 1.1
This approach is not suitable for always because there is a reason for this.
Let’s see the following example.
import ast qton = 11 print(ast.literal_eval(qton))
The Str() function converts 11 integers to float, but ast.literal_eval() function throws a ValueError here. Run the program, and you will get the following.
Traceback (most recent call last): File "app.py", line 5, in <module> print(ast.literal_eval(qton)) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 96, in literal_eval return _convert(node_or_string) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 95, in _convert return _convert_signed_num(node) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 74, in _convert_signed_num return _convert_num(node) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py", line 66, in _convert_num raise ValueError('malformed node or string: ' + repr(node)) ValueError: malformed node or string: 11
See, you got ValueError: malformed node or String: 11.
This is not an excellent solution to the problem.
Python float to string
To convert float to string in Python, use the str() function. The str() is a built-in Python function that converts the specified value into a string. The str() function might be required sometimes when we want to concatenate float values.
# app.py pton = 1.1 qton = 1.11 zton = 1.111 print(f'Concatenation of {pton} and {qton} is {str(pton) + str(qton)}') print( f'Data from {pton}, {qton} and {zton}:\n{str(pton)},{str(qton)},{str(zton)}') print( f'Data from {pton}, {qton} and {zton}:\n{", ".join([str(pton),str(qton),str(zton)])}')
Output
Concatenation of 1.1 and 1.11 is 1.11.11 Data from 1.1, 1.11 and 1.111: 1.1,1.11,1.111 Data from 1.1, 1.11 and 1.111: 1.1, 1.11, 1.111
Conclusion
Python float() function converts String to Float data type.
Python str() function can convert Float to String data type.