Python defines type conversion functions to directly convert one data type to another which is useful in day to day and competitive programming.
Example 1 :
#int(a,base) : This function converts any data type to integer.
#‘Base’ specifies the base in which string is if data type is string.
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", c)
After converting to integer base 2 : 18
Example 2:
#float() -> This function is used to convert any data type to a floating point number
e = float(s)
print ("After converting to float : ", e)
After converting to float : 10010.0
Example 3:
#tuple() -> This function is used to convert to a tuple.
#set() -> This function returns the type after converting to set.
#list() -> This function is used to convert any data type to a list type.
# initializing string
s = 'python'
# printing string converting to tuple
c = tuple(s)
print ("After converting string to tuple : ",c)
# printing string converting to set
c = set(s)
print ("After converting string to set : ",c)
# printing string converting to list
c = list(s)
print ("After converting string to list : ",c)
After converting string to tuple : ('p', 'y', 't', 'h', 'o', 'n')
After converting string to set : {'p', 'n', 'y', 'o', 't', 'h'}
After converting string to list : ['p', 'y', 't', 'h', 'o', 'n']
Example 4:
#dict() -> This function is used to convert a tuple of order (key,value) into a dictionary.
#str() -> Used to convert integer into a string.
#complex(real,imag) -> This function converts real numbers to complex(real,imag) number.
# initializing integers
a = 1
b = 2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
# printing integer converting to complex number
c = complex(1,2)
print ("After converting integer to complex number : ",c)
# printing integer converting to string
c = str(a)
print ("After converting integer to string : ",c)
# printing tuple converting to expression dictionary
c = dict(tup)
print ("After converting tuple to dictionary : ",c)
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}