Type Conversion and Type Casting in Python

Spread the love

In Python, it is just not possible to complete certain operations that involves different types of data. For example it is not possible to add a string and an integer together.

In [1]: "5" + 10
Traceback (most recent call last):

  File "/var/folders/v4/fwpsf7y53k1bf_bpgynnxkhc0000gn/T/ipykernel_2532/1055879372.py", line 1, in <module>
    "5" + 10

TypeError: can only concatenate str (not "int") to str

The reason the above statement result in error because 5 is a string and 10 is an integer. But we can convert the string to int using type casting in python.

In [2]: int("5") + 10
Out[2]: 15

In the above statement int(“5”) first convert the string to integer type and then does the addition.

Python provides several built-in functions to convert a value from one data type to another. These functions return a new object representing the converted value.

Functions for Type Conversions –

FunctionDescription
int(x)Converts x to an integer
long(x)Converts x to a long integer
float(x)Converts x to a floating point number
str(x)Converts x to a string
tuple(x)Converts x to a tuple
list(x)Converts x to a list
set(x)Converts x to a set
ord(x)Converts a single character to its integer value
oct(x)Converts an integer to an octal string
hex(x)Converts an integer to a hexadecimal string
chr(x)Converts an integer to a character
unichar(x)Converts an integer to a Unicode Character
dict(x)creates a dictionary if x forms a (key-value) pair

However, before using type conversion to convert a floating point number into an integer number, remember that int() converts a float to an int by truncation (discarding the fractional part) and not by rounding to the nearest whole number. The round() works more appropriately by rounding a floating point number to the nearest integer as shown below.

In [3]: int(5.7)
Out[3]: 5

In [4]: round(5.7)
Out[4]: 6

Note that each argument passed to a function has a specific data type. If you pass an argument of the wrong data type to a function, it will generate an error. For example you can not find the square root of a string. If you don’t know what type of arguments a function accepts, then you should use the help() before using the function.

Type casting vs Type Coercion –

So far we have done explicit conversion of a value from one data type to another. This is know as type casting. However in most of the programming language including Python, there is an implicit conversion of data types either during compilation or during run time. This is also know as Type coercion. For example, in an expression that has integer and floating point numbers like (5.7 + 3) gives 8.7, the compiler will automatically convert the integer into floating point number so that fractional part is not lost.

In [5]: 5.7 + 3
Out[5]: 8.7

Related Posts –

  1. Data types in Python

Rating: 1 out of 5.

Leave a Reply