Type Conversion in Python
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to another which is useful in
day-to-day and competitive programming. This article is aimed at providing information about certain
conversion functions.
Example
As we can see the data type of ‘z’ got automatically changed to the “float” type while one variable x is
of integer type while the other variable y is of float type. The reason for the float value not being
converted into an integer instead is due to type promotion that allows performing operations by
converting data into a wider-sized data type without any loss of information. This is a simple case of
Implicit type conversion in Python.
Python3
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z = x + y
print(z)
print("z is of type:",type(z))
Output
int(a, base): This function converts any data type to an integer. ‘Base’ specifies the base in which the
string is if the data type is a string.
float(): This function is used to convert any data type to a floating-point number.
Python3
# initializing string
s = "10010"
Python3
# initializing integer
s = '4'
Output:
Python3
# initializing string
s = 'geeks'
Output:
dict(): This function is used to convert a tuple of order (key, value) into a dictionary.
str(): Used to convert an integer into a string.
complex(real,imag) : This function converts real numbers to complex(real,imag) number.
Python3
# initializing integers
a = 1
b = 2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
Output:
Python3
a = chr(76)
b = chr(77)
print(a)
print(b)
Output:
L
M