Type Conversion in Python: Types and Examples

Type Conversion in Python: Types and Examples

4 mins read3.4K Views Comment
clickHere
Updated on Aug 2, 2022 13:18 IST

Type conversion in Python refers to the direct conversion of object of one data type to another data type. In this conversion, Python interpreter automatically performs conversion.

2022_08_Type-Conversion-in-Python.jpg

In Python, we have the flexibility to convert one data type to another using a specific function. On top of that, we do not need to explicitly define the data type while declaring variables unlike other programming languages like C++ and Java.

In this article, we will explore the concept of type conversion in python. So, Python has two types of data type conversions:

Let’s deep dive into each one of them.

Implicit Type Conversion

For implicit type conversion, the python interpreter automatically assigns a data type to a variable once it is declared. For instance, if we have a variable x and we assign the value 10 to it, the variable x automatically becomes an integer datatype. Take a look at the below examples for a better understanding.

Example 1:

 
# declare a varable with
# integer value
x = 10
# check type of x
print ("x is of type:", type(x))
Copy code

Output:

 
x is of type: <class 'int'="">
Copy code

As you can observe in the above example, we didn’t specify the type of x before declaring it, but based on the value of x, the Python interpreter automatically assigned it as an integer data type.

Example 2:

 
# variable with integer value
a = 10
# variable with decimal/float value
b = 10.00
# variable with string value
c = "Ten"
# variable with list as value
d = [10]
# variable with tuple as value
e = ()
# variable with boolean value
f = True
# variable with NoneType as value
g = None
# check type of a
print ("a is of type:", type(a))
# check type of b
print ("b is of type:", type(b))
# check type of c
print ("c is of type:", type(c))
# check type of d
print ("d is of type:", type(d))
# check type of e
print ("e is of type:", type(e))
# check type of f
print ("f is of type:", type(f))
# check type of g
print ("g is of type:", type(g))
Copy code

Output:

 
a is of type: <class 'int'>
b is of type: <class 'float'>
c is of type: <class 'str'>
d is of type: <class 'list'>
e is of type: <class 'tuple'>
f is of type: <class 'bool'>
g is of type: <class 'NoneType'>
Copy code
Comparison Operators in Python
Comparison Operators in Python
Operators are symbols that are used to perform operation on variables and values. In this article we will discuss comparison operators in Python.
Learning All About Python if else Statement
Learning All About Python if else Statement
The concept of Python if else statement works on the logic that a piece of code will be executed only if a certain condition is true, else not.
Abstraction in Python
Abstraction in Python
In this article, we will discuss abstraction in python and how to implement abstraction using abstract classes and methods.

Explicit Type Conversion

In Explicit type conversion, we manually alter the datatype of a Python object to suit our purpose. For this, we make use of various in-built functions. It is also important to note that, since we forcefully change the data type of the object, there is some risk of data loss. 

Let’s take a look at the in-built functions used or explicit type conversion in python.

1. Int(a base): This function is used to explicitly convert any numeric data type into an integer data type. It takes a python object and the numerical base as a parameter. A base parameter is an option. By default, it takes base 10.

Example:

 
# initialize a float/decimal
x = 123.321
# check current datatype of x
print('x is of type:',type(x))
# convert float into integer type
x = int(x)
# check converted type of x
print('Converted x is of type:', type(x))
Copy code
 
x is of type: <class 'float'="">
Converted x is of type: <class 'int'="">
Copy code

2. float(): This function is used to convert any numeric data type to a floating type number.

Example:

 
# initialize an integer type
x = 123
# check current datatype of x
print('x is of type:',type(x))
# convert integer into float type
x = float(x)
# check converted type of x
print('Converted x is of type:', type(x))
Copy code

Output:

 
x is of type: <class 'int'="">
Converted x is of type: <class 'float'="">
Copy code

Explore Python courses

3. complex(real_numb, imaginary_numb): This function is used to convert real numbers to complex numbers. The first parameter it takes is the real number and the second parameter is the imaginary number.

Example:

 
# initialize a real numbee
x = 100
# initialize cofficient for
# the imaginary number
y= 5
# check current datatype of x
print('x is of type:',type(x))
# convert x into complex type
x = complex(x,y)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'int'="">
Converted x is of type: <class 'complex'="">, Value :(100+5j)
Copy code

4. str(): This function is used to convert any data type to string type.

Example:

 
# initialize an integer type
x = 100
# check current datatype of x
print('x is of type:',type(x))
# convert integer into string type
x = str(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'int'="">
Converted x is of type: <class 'str'="">, Value :100
Copy code

5. list(): This function is used for type conversion to list data type.

6. tuple(): This function is used for type conversion to tuple data type.

7. set(): This function is used for type conversion to set data type.

Example: 

 
# initialize a string type
x = "Naukri"
# check current datatype of x
print('x is of type:',type(x))
# convert string into list type
x = list(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
# convert string into tuple type
x = tuple(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
# convert string into set type
x = set(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'str'="">
Converted x is of type: <class 'list'="">, Value :['N', 'a', 'u', 'k', 'r', 'i']
Converted x is of type: <class 'tuple'="">, Value :('N', 'a', 'u', 'k', 'r', 'i')
Converted x is of type: <class 'set'="">, Value :{'a', 'N', 'i', 'r', 'k', 'u'}
Copy code

8. dict(): This function is used to convert an ordered tuple(ie, tuple with key, value) into a dictionary.

Example:

 
# initialize an ordered tuple type
x = (('a',1),('b',2),('c',3),('d',4))
# check current datatype of x
print('x is of type:',type(x))
# convert tuple into dictionary type
x = dict(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'tuple'="">
Converted x is of type: <class 'dict'="">, Value :{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Copy code

9. hex(): This function is used to convert integers to hexadecimal strings.

Example:

 
# initialize an integer type
x = 100
# check current datatype of x
print('x is of type:',type(x))
# convert integer into hexadecimal string type
x = hex(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'int'="">
Converted x is of type: <class 'str'="">, Value :0x64
Copy code

10. oct(): This function is used to convert integers to octal strings.

Example:

 
In this example, we will convert an integer to an octal string.
# initialize an integer type
x = 100
# check current datatype of x
print('x is of type:',type(x))
# convert integer into octal string type
x = oct(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", Value :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'int'="">
Converted x is of type: <class 'str'="">, Value :0o144
Copy code

11. ord(): This function is used to convert a single character to its corresponding ASCII number

Example:

 
# initialize an single
# character string type
x = "A"
# check current datatype of x
print('x is of type:',type(x))
# convert integer into numeric type
x = ord(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", ASCII Value :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'str'="">
Converted x is of type: <class 'int'="">, ASCII Value :65
Copy code

As you can see in the above example, the String “A” got converted into its respective ASCII value of 65.

12. chr(number): This function is used to convert numbers into their corresponding ASCII character. It takes the number as a parameter.

Example:

 
# initialize an integer type
x = 76
# check current datatype of x
print('x is of type:',type(x))
# convert integer into ASCII character
x = chr(x)
# check converted type of x
print('Converted x is of type:', type(x), end=", ASCII Character :")
# value of converted x
print(x)
Copy code

Output:

 
x is of type: <class 'int'="">
Converted x is of type: <class 'str'="">, ASCII Character :L
Copy code

Conclusion:

In this article, we have managed to cover the following concepts:

  • Types of data type conversion in Python
  • Implicit type conversion in python with examples
  • Explicit type conversion in Python with examples
  • Explored use cases of both Implicit and Explicit Type conversion

_______________

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio