Python Type Conversion

In this Python article, we will discuss how to convert from one data type to another in Python.

We learned about Python data types in one of our previous articles. So here we will see how to juggle between different data types.

The process of converting one data type to another data type is called type conversion. In python there are two types of type conversion:

  1. Implicit type conversion
  2. Explicit type conversion or typecasting

1. Implicit Data Type Conversion

When the data type conversion happens during compilation or on run time and the interpreter automatically converts one data type into another(required) data type then it’s called implicit data type conversion.

When constants and variables of different types are mixed in an expression, they are all converted to the same type (provided automatic conversion is possible within the data types).

Let’s implement an example by adding two python variables of different data types and store it in another variable. Then we will check if the python compiler is able to change the data type of the resultant or not.

integer = 2 
decimal = 5.0
x = decimal + integer
print("Type after adding both values :")
Type after adding both values :
< class 'float' >

Why did python convert the resultant into float and not integer?

It’s because if python would have converted the resultant into the integer then the floating value would have been removed and there would be data loss. So in order to prevent data loss, python always converts smaller data types into larger data types.

Let’s see another example by adding string data type to integer type

string = "2" 
integer = 5
x = string + integer
Traceback (most recent call last):
  File "<stdin>", line 1, in 
TypeError: can only concatenate str (not "int") to str

As Python does not support type coercion (in this case automatic conversion from string to int), when we try to add a string with an integer then the compiler gives an error, and to resolve this issue python has a concept of Explicit data type conversion.

2. Explicit Data Type conversion

Explicit data type conversion is defined as the process where the user defines the conversion of one data type to another as per the requirements.

It is also known as typecasting as we are casting(changing) the type of data.

The general form of type casting or explicit data type conversion is:


Let’s discuss some in-built functions for type-casting by implementing examples.

2.1. Convert Any data type to int()

Every numerical value has a base, for example.

  • Decimal value or just integer has a base of 10
  • The binary value uses the digits 0 or 1 and has a base of 2
  • The octal value uses the digits through 0 to 7 and has a base of 8
  • Hexadecimal uses the digit through 0 to 9 plus the letters A through F, and have a base of 16

Syntax : int(expression , base) , int(expression)

Note: By default the base of int is 10 which is decimal value.

a = 2.5
b = "0101"
c= "0101"
print("After converting a to int with base 10 --> ", int(a))
print("After converting b to int with base 2 --> ", int(b, 2))
print("After converting c to int without base --> ", int(c))
After converting a to int with base 10 --> 2
After converting b to int with base 2 --> 5
After converting c to int without base --> 101

2.2. Convert Any data type to float()

Let’s try to convert some data types into float data type.

Syntax : float(expression)

a = 2
b = "0101"
print("After converting 'a' to float --> ", float(a))
print("After converting 'b' to float --> ", float(b))
After converting 'a' to float --> 2.0
After converting 'b' to float --> 101.0

2.3. ord()

ord() function is used to convert character into integer.

Syntax : ord(character)

a = 'A'

2.4. chr()

chr() function works opposite of ord() function as it is used to convert an integer into a character.

Syntax : chr(integer)

a = 65

2.5. hex()

The hex() function is used to convert integers into hexadecimal strings.

Syntax : hex(integer)

a = 75

2.6. oct()

oct() function is used to convert integer into octal string.

Syntax : oct(integer)

a = 75

2.7. tuple()

tuple() function is used to convert a data type into tuple.

Syntax : tuple(expression)

a = "McDreamy"

b = [10,7,"It's a beautiful day to save lives",2.0]
('M', 'c', 'D', 'r', 'e', 'a', 'm', 'y')
(10, 7, "It's a beautiful day to save lives", 2.0)

2.7. set()

The set() function is used to convert a data type into the set. Most of the time we use a set to get unique values.

Syntax : set(expression)

a = "Codingeek"

b = [10,7,10,"It's a beautiful day to save lives",2.0]
{'i', 'C', 'd', 'g', 'e', 'k', 'n', 'o'}
{"It's a beautiful day to save lives", 10, 2.0, 7}

2.8. list()

list() function is used to convert a data type into a list.

Syntax : list(expression)

a = "Codingeek"

b = [10,7,10,"It's a beautiful day to save lives",2.0]
['C', 'o', 'd', 'i', 'n', 'g', 'e', 'e', 'k']
[10, 7, 10, "It's a beautiful day to save lives", 2.0]

2.9. dict()

dict() function is used to convert a tuple of key-value pairs into a dictionary.

Syntax : dict(expression)

a = ((1,"Ross"),(2,"Rachel"),(3,"Friends"))

b = [[1,"Meredith"],[2,"Hayes"],[3,"Friends"]]
{1: 'Ross', 2: 'Rachel', 3: 'Friends'}
{1: 'Meredith', 2: 'Hayes', 3: 'Friends'}

2.10. str()

str() function is used to convert numeric into a string.

Syntax : str(numeric)

a = 10125

b = str(b)
print(type(b), b)
<class 'str'> [1,2,3,1,4]

2.11. complex(real,imag)

complex() function is used to convert a real number into a complex number.

Syntax : complex(real_value, image_value)

a = complex(2,5)

3. How chr() is different from str() ?

chr() function converts an integer into its equivalent ASCII value whereas str() returns the string representation of an object.

a = 65

print("Using char() 65 = ", chr(a))
print("Using str()  65 = ", str(a))
Using char() 65 =  A
Using str()  65 =  65

4. Conclusion

In this article we have discussed in detail about

  • Different types of conversion
  • In-built functions for type conversion
  • Difference between chr() and str()

Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books

An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments
Mohammad Imran
2 years ago

Hey Lakshika! Great and consice explanation with appropriate examples. I think this article should rank higher.
Thanks for sharing this article.

Last edited 2 years ago by Mohammad Imran
Would love your thoughts, please comment.x