Type Conversion in Python: Types and Examples
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.
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 valuex = 10
# check type of xprint ("x is of type:", type(x))
Output:
x is of type: <class 'int'="">
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 valuea = 10
# variable with decimal/float valueb = 10.00
# variable with string valuec = "Ten"
# variable with list as valued = [10]
# variable with tuple as valuee = ()
# variable with boolean valuef = True
# variable with NoneType as valueg = None
# check type of aprint ("a is of type:", type(a))# check type of bprint ("b is of type:", type(b))# check type of cprint ("c is of type:", type(c))# check type of dprint ("d is of type:", type(d))# check type of eprint ("e is of type:", type(e))# check type of fprint ("f is of type:", type(f))# check type of gprint ("g is of type:", type(g))
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'>
Best-suited Python courses for you
Learn Python with these high-rated online courses
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/decimalx = 123.321 # check current datatype of xprint('x is of type:',type(x)) # convert float into integer typex = int(x)
# check converted type of xprint('Converted x is of type:', type(x))
x is of type: <class 'float'="">Converted x is of type: <class 'int'="">
2. float(): This function is used to convert any numeric data type to a floating type number.
Example:
# initialize an integer typex = 123 # check current datatype of xprint('x is of type:',type(x)) # convert integer into float typex = float(x)
# check converted type of xprint('Converted x is of type:', type(x))
Output:
x is of type: <class 'int'="">Converted x is of type: <class 'float'="">
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 numbeex = 100
# initialize cofficient for# the imaginary numbery= 5
# check current datatype of xprint('x is of type:',type(x)) # convert x into complex typex = complex(x,y)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
Output:
x is of type: <class 'int'="">Converted x is of type: <class 'complex'="">, Value :(100+5j)
4. str(): This function is used to convert any data type to string type.
Example:
# initialize an integer typex = 100 # check current datatype of xprint('x is of type:',type(x)) # convert integer into string typex = str(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
Output:
x is of type: <class 'int'="">Converted x is of type: <class 'str'="">, Value :100
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 typex = "Naukri" # check current datatype of xprint('x is of type:',type(x)) # convert string into list typex = list(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
# convert string into tuple typex = tuple(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
# convert string into set typex = set(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
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'}
8. dict(): This function is used to convert an ordered tuple(ie, tuple with key, value) into a dictionary.
Example:
# initialize an ordered tuple typex = (('a',1),('b',2),('c',3),('d',4)) # check current datatype of xprint('x is of type:',type(x)) # convert tuple into dictionary typex = dict(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
Output:
x is of type: <class 'tuple'="">Converted x is of type: <class 'dict'="">, Value :{'a': 1, 'b': 2, 'c': 3, 'd': 4}
9. hex(): This function is used to convert integers to hexadecimal strings.
Example:
# initialize an integer typex = 100 # check current datatype of xprint('x is of type:',type(x)) # convert integer into hexadecimal string typex = hex(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
Output:
x is of type: <class 'int'="">Converted x is of type: <class 'str'="">, Value :0x64
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 typex = 100 # check current datatype of xprint('x is of type:',type(x)) # convert integer into octal string typex = oct(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", Value :")
# value of converted xprint(x)
Output:
x is of type: <class 'int'="">Converted x is of type: <class 'str'="">, Value :0o144
11. ord(): This function is used to convert a single character to its corresponding ASCII number
Example:
# initialize an single# character string typex = "A" # check current datatype of xprint('x is of type:',type(x)) # convert integer into numeric typex = ord(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", ASCII Value :")
# value of converted xprint(x)
Output:
x is of type: <class 'str'="">Converted x is of type: <class 'int'="">, ASCII Value :65
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 typex = 76 # check current datatype of xprint('x is of type:',type(x)) # convert integer into ASCII characterx = chr(x)
# check converted type of xprint('Converted x is of type:', type(x), end=", ASCII Character :")
# value of converted xprint(x)
Output:
x is of type: <class 'int'="">Converted x is of type: <class 'str'="">, ASCII Character :L
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
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