Type Casting
There are few ways in which we force and convert our data type into another data type. The process of converting one data type to another is known as type casting.
int() function
This function is used to convert any floating point number or numeric value represented as string into an integer value.
Syntax for using int function:
int(x)
We have passed our number 'x' as a parameter inside the int function. It will convert it into an integer and will return the result.
Example:
>>> a = 2.4 >>> a = int(a) >>> a output: 2 >>> str = '2' >>> str = int(str) >>> str output: 2
float() function
This function is used to convert any integer or numeric value represented as string into a floating point number.
Syntax for using float function:
float(x)
We have passed a value 'x' as a parameter inside the float function. It will convert it into a floating point number and will return the result.
Example:
>>> a = 3 >>> a = float(a) >>> a output: 3.0 >>> str = '12.47' >>> str = float(str) >>> str output: 12.47
complex() function
This is used to convert any integer, float or numeric string into complex number.
Syntax for using float function:
complex(x) or complex(x, y)
Passing just one parameter results in complex number having imaginary part value as 0. In case you pass a parameter value appended with 'j', then the real part will become zero. You can also pass a string as a parameter.
Example:
>>> a = 3 >>> a = complex(a) >>> a output: 3+0j >>> b = '1+2j' >>> b = complex(b) >>> b output: 1+2j
In case of passing two parameters inside complex function, the first parameter becomes real part and second parameter becomes imaginary part of the complex number.
Example:
>>> a = 3 >>> b = 4 >>> c = complex(a,b) >>> c output: 3+4j
str() function
This function is used to convert any value passed inside it as a string.
Syntax for using str function:
str(x)
We have passed a value 'x' as a parameter inside the str function. It will convert it into a string and will return the result.
Example:
>>> a = 1 >>> a = str(a) >>> a output: '3' >>> list = [1,2,3] >>> str = str(list) >>> str output: '[1,2,3]'
There are other functions like list(), tuple() and dict() to convert strings, lists, tuples and dictionary into desired data-types. We will discuss them later. If you are curious about them then feel free to try them.