Convert String to Float in PythonWe are quite familiar with the data types available in Python and what kind of different operations we can perform on them. We know that, Strings are a sequence of characters that are denoted using inverted commas ''. They are immutable which means they cannot be changed once declared. And float values are nothing but the decimal values. We can check the types using the program given below- Output: <class 'float'> <class 'str'> In this tutorial, we will discuss the different scenarios of converting a string to float in Python.
Using Float FunctionLet us look at the first case where we will use the float function, The following program illustrates the same- Output: The float value is 2.71 Explanation: Let's understand what we have done in the above program-
Converting a String with CommasLet us look at the second case where we will convert a string with commas, The following program illustrates the same- Output: The float value is 2.71 Explanation: Let's understand what we have done in the above program-
Converting to a Float ListLet us look at the third case where we will convert the string to a float list, The following program illustrates the same- Output: The list having float values: [ 1.21, 2.34, 3.42, 9.22, 5.43] Explanation: Let's understand what we have done in the above program-
Converting List of Strings to FloatLet us look at the fourth case where we will convert list of strings to float, The following program illustrates the same- Output: The list having float values: [ 1.21,2.34,3.42,9.22,5.43] Let's understand what we have done in the above program-
Converting Using NumPyLet us look at the fifth case where we will convert the string using numpy, The following program illustrates the same- Output: The list having float values: [1.21 2.34 3.42 9.22 5.43 ] Explanation: Let's understand what we have done in the above program-
Converting in Specified Decimal PointsFinally, in the last program we will see how we can convert a string to specified decimal points, The following program illustrates the same- Output: 2.89 Explanation: Let's understand what we have done in the above program-
ConclusionSo, in this tutorial, we understood the different scenarios and learned approaches to convert a string to float in Python. Next TopicDecorators with Parameters in Python |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India