Type Conversion in Python with Example.

How to convert Data Type in Python with Example?

Hi everyone, in this article, we’ll be understanding data type conversion functions with basic definitions and examples.

Let’s get started!

What is Data Type Conversion in Python?

Python defines data type conversion functions like int(), float(), str(), etc to convert one data type to another. Understanding and knowing these functions are important since this comes in handy in day-to-day and competitive programming.

There are two types of Type Conversion in Python:

1. Implicit Type Conversion :-

In Implicit type conversion, the Python interpreter itself automatically converts one data type to another without any manual intervention by the user.

Example:-

#!/usr/local/bin/python3
a = 9
print("Data Type of Variable a :",type(a))
b = 5.2
print("Data Type of Variable b :",type(b))
a = a + b
print("\nValue of a :",a)
print("*Updated Data Type of Variable a :",type(a))

OutPut:

Data Type of Variable a : <class ‘int’>
Data Type of Variable b : <class ‘float’>
Value of a : 14.2
*Updated Data Type of Variable a : <class ‘float’>

As we can see from the above example initially the data type of variable “a” is int and variable “b” is float. After performing the summation operation and storing the result in variable “a”, the datatype of “a” automatically gets updated to float datatype.  This is what is known as Implicit type conversion in the python programming language.

2. Explicit Type Conversion :-

The name itself suggested that one needs to clearly state the needed data type conversion. There is no automatic data type conversion which was the case above (i.e Implicit Data Type Conversion), Explicit data type conversion you need to manually change the data type to another data type as per requirement.

Let’s understand each type of explicit conversion function offered by python with a simple example.

int()

This function is used to convert any data type into an integer data type. The syntax of int() is int(variable, base), the function takes 2 parameters. where “variable” is a string and ‘base’ specifies the base in which string is if the data type is a string.

# Python code to demonstrate Type conversion
# using int()
#example_1
str_num = "58"
print("Data Type of Variable str_num (before conversion):",type(str_num))
num = int(str_num)
print("\nData Type of Variable str_num (after conversion):",type(num))
# example_2
str_num = "11010"
# using int(string,base)
num = int(str_num,2)
print ("\nAfter converting to integer base 2 : ", num)

float()

This function is used to convert any data type into float type. The syntax of float() is float(parameter), where parameter is optional. The use of float without parameters is only to declare an empty float data type variable.

# Python code to demonstrate Type conversion
# using float()
#example_1
str_num = "93"
print("Data Type of Variable str_num (before conversion) : %s and str_num value : %s "%(type(str_num),str_num))
num = float(str_num)
print("\nData Type of Variable str_num (after conversion): %s and num value : %s "%(type(num),num))
 

ord()

This function is used to convert characters into integers. This function takes one parameter which is a character (i.e ord(character) and converts it into its Unicode code value. This function is used to check whether a string contains a special character (like emojis). This function can be used on only one character.

# Python code to demonstrate Type conversion
# using ord()
#example_1
character = "J"
unicode_char = ord(character)
print("\nUnicode of character %s is %s "%(character,unicode_char))

hex()

This function is used to convert integers to hexadecimal. This function also takes a single argument (integer or float) and returns a hexadecimal value. The syntax of the hex() function is hex(parameter).

# Python code to demonstrate Type conversion
# using hex()
#example_1
n = 56
hexadecimal_n = hex(n)
print("\nHexadecimal of integer %s is %s "%(n,hexadecimal_n))
 
 

oct()

This function is used to convert integer to octal. This function also takes a single argument (only integer data type) and returns an octal value. The function syntax is oct(argument).

# Python code to demonstrate Type conversion
# using oct()
#example_1
n = 47
octal_value = hex(n)
print("\nOctal of integer %s is %s "%(n,octal_value))
 
 

tuple()

This function is used to convert the value to a tuple. Tuples are used to store multiple items in a variable. The syntax of tuple() function is tuple(argument) and tuple looks like (“one”, “two”, “three”). A tuple is a collection of values that are ordered and unchangeable(i.e immutable).

# Python code to demonstrate Type conversion
# using tuple()
 
#declaring an empty tuple.
tuple_1 = tuple()
print('\ntuple_1 = ', tuple_1)
 
# creating a tuple from a string
tuple_2 = tuple('Jeevan')
print('tuple_2 = ',tuple_2)
 
# creating a tuple from a list
tuple_3 = tuple([1, 4, 6])
print('tuple_3 = ', tuple_3)
 
tuple_3 = tuple([1, 4, 6, "one"])
print('tuple_3 = ', tuple_3)
 
# creating a tuple from a dictionary
tuple_4 = tuple({1: 'one', 2: 'two'})
print('tuple_4 = ',tuple_4)
 
 

set()

This function returns the type after converting to set. The syntax of set() is set(iterable), passing parameters is optional. Note that sets are unordered. Set is represented by {value1, value2, value3,….. valueN).

# Python code to demonstrate Type conversion
# using set()
 
#declaring an empty tuple.
set_1 = set()
print('\nset_1 = ', set_1)
 
# creating a set from a string
set_2 = set('Jeevan')
print('set_2 = ',set_2)
 
# creating a set from a list
set_3 = set([1, 4, 6])
print('set_3 = ', set_3)
 
tuple_3 = set([1, 4, 6, "one"])
print('tuple_3 = ', tuple_3)
 
# creating a set from a dictionary
set_4 = set({1: 'one', 2: 'two'})
print('set_4 = ',set_4)
 
# creating a set from a tuple
set_5 = set((3, 7, 8))
print('set_5 = ', set_5)

list()

This function is used to convert any data type to a list type i.e creates a list object. Lists are ordered and mutable (i.e changeable). Syntax of list() is list(parameter) and a list is represented as [‘one’, 2, ‘three’]. The parameter is optional and can be a sequence (string, tuples) or collection (set, dictionary), or an iterator object.

# Python code to demonstrate Type conversion
# using list()
 
#declaring an empty list.
list_1 = list()
print('\nlist_1 = ', list_1)
 
# creating a list from a string
list_2 = list('Jeevan')
print('list_2 = ',list_2)
 
# creating a list from a set
list_3 = list({1, 4, 6})
print('list_3 = ', list_3)
 
list_3 = list({1, 4, 6, "one"})
print('list_3 = ', list_3)
 
# creating a list from a dictionary
list_4 = list({1: 'one', 2: 'two'})
print('list_4 = ',list_4)
 
# creating a list from a tuple
list_5 = list((3, 7, 8))
print('list_5 = ', list_5)
 
 

dict()

This function is used to convert a tuple of order (key, value) into a dictionary. dict() is a constructor which creates a dictionary. That means if no argument passed it creates an empty dictionary. Syntax of dict() is dict(parameter) where parameter is optional. Given a parameter, it converts it into a dictionary format and if the parameter is not passed an empty dictionary object is created.

# Python code to demonstrate Type conversion
# using dict()
 
#declaring an empty list.
dict_1 = dict()
print('\ndict_1 = ', dict_1)
 
dict_2 = dict(a=1, A='One', b=2)
print('dict_2 = ',dict_2)
 
dict_3 = dict({'a': 5, 'name': 'Jeevan'}, num=20)
print('dict_3 = ', dict_3)
 
dict_3 = dict([(1, 'One'), ['Two', 2], [3,'Three']])
print('dict_3 = ', dict_3)
 
dict_4 = dict(((1, 'one'), (2,'two')))
print('dict_4 = ',dict_4)

There are 4 built-in data types in Python used to store collections of data, those are Tuple, List, Set, and Dictionary, all with different qualities and usage.

str()

Used to convert an integer into a string. This function is mostly used when we need to combine different data type values with string data type values. Syntax of str() function is str(parameter).

# Python code to demonstrate Type conversion
# using str()
#example_1
num = 66
print("\nData Type of Variable num (before conversion):",type(num))
str_num = str(num)
print("Data Type of Variable str_num (after conversion):",type(str_num))
a = "string number combination -> "+str_num
print(a)

chr()

This function converts a number to its corresponding ASCII character. The syntax of function chr() is chr(number) and integer number is a must. Also if you passed an integer that is outside the range then the method returns a ValueError.

# Python code to demonstrate Type conversion
# using chr()
 
#example_1
num = 67
character = chr(num)
print("\n Corresponding ASCII value is %s for number : %s"%(num,character))
 
#example_2
num = 187
character = chr(num)
print("\n Corresponding ASCII value is %s for number : %s"%(num,character))
 
 

Leave a Reply

Your email address will not be published. Required fields are marked *