Conversion in Python : float to string and others:
Python defines type conversion functions to directly convert one data type to another
First let's discuss the int and float functions. The int function converts any data type to
integer. And float function is used to convert any
data type to a floating point number Here's an example. We have declare a string
"1001". Now, we are converting it to integer with base 2 and base 10.
Let's run this code. We can see that the output is 9 and 1001. As they are the binary and
decimal conversion of string 1001. Now, let's convert this string to float by
using the float function. Let's run this code again, we can see that string 1001 is converted
to float. Now, let's discuss ord(), hex() and oct()
functions. ord() function converts a character to it's ASCII integer value.
Whereas, hex() and oct() converts an integer to its hexadecimal and octal string.
Here we are printing the ASCII value of the character space and after this we printing
hexadecimal and octal conversion of the number 56.
Let's run this code, we can see that ASCII value of space is 32. And integer 56 is converted
to its hexadecimal and octal string. Now, let's discuss the tuple(), set() and
list() functions. These functions are used to convert a datatype to tuple(), set() and
list() functions respectively. Here we have a string 'Geeks' and converting
it into tuple,set and list. Let's run this code. We can see that string
geeks is converted to tuple, set and list in the output as they have their respective
parenthesis. Now, let's discuss the complex and str functions.
Complex function converts real numbers to complex(real,imag) number and str function
is used to convert a datatype into a string. Here we are passing 1 and 2 in the complex
function and here we are converting the number 1211 into string using str function and printing
the first two characters of the string. Let's run this code, we can see that the ouput
is 1 + 2j and first two characters of the number 1211 i.e 1 and 2.
So, we discussed data type conversion in Python.