Table of content

How to Typecast in Python?

Typecasting or Type Conversion refers to converting an entity from one data type to another data type. There are two types of typecasting operations.

  1. Implicit Type Conversion
  2. Explicit Type Conversion

In the implicit type casting, the python interpreter automatically converts an entity from one data type to another data type.

Example 1: Conversion of Integer to float data type

Consider two variables a = 2(Integer data type) and b = 2.5(float data type) . The addition of both the variables gives the output as 4.5(float data type).

The python interpreter returns the result in float data type because if the output was converted to integer data type the result of addition will be 4 leading to loss of the fractional part. To prevent the loss of data python always converts smaller data types(integer) to larger data types(float).

a = 2
print("Type of 'a' : ", type(a))
b = 2.5
print("Type of 'b' : ", type(b))
add = a + b
print("addition : ", add)
print("Type of 'add' : ", type(b))

Output

Type of 'a' :  <class 'int'>
Type of 'b' :  <class 'float'>
addition :  4.5
Type of 'add' :  <class 'float'>
Example 2: Addition of an integer and string data type.

Consider two variables a = '5' (string data type) and b = 10 (Integer data type). The addition of variables a and b raises a TypeError exception. Python interpreters cannot use implicit typecasting to convert string to integer or float and vice versa.

a= '5'
print("Type of 'a' : ", type(a))
b = 10
print("Type of 'b' : ", type(b))
add = a +b
print("addition : ", add)
print("Type of 'add' : ", type(b))

The above code returns the output as

Type of 'a' :  <class 'str'>
Type of 'b' :  <class 'int'>
add = a +b
TypeError: can only concatenate str (not "int") to str

In such conditions, explicit type conversion comes into play.

Explicit Type Conversion

In explicit type conversion, we use built-in functions like int(), float(), str(), etc to convert one data type to another.

Converting a float or string to integer data type using int() function.

The int() function converts floating-point values to an integer value by trimming the fractional part and strings to integer data type provided that the string given is a whole number.

num_float = 5.67
type_int = int(num_float)
print("converting float to int: ", type_int)
print("Data type of type_int: ", type(type_int))
num_string = '123'
type_int = int(num_string)
print("converting string to int: ", type_int)
print("Data type of type_int' : ", type(type_int))

The above code gives output as

converting float to int:  5
Data type of type_int:  <class 'int'>
converting string to int:  123
Data type of type_int :  <class 'int'>
If the string contains decimal values and we use the int() function to get the integer value, the program raises the ValueError exception.

Example,

num_string = '123.765'
type_int = int(num_string)
print("converting string to int: ", type_int)

Output

type_int = int(num_string)
ValueError: invalid literal for int() with base 10: '123.765'
To convert a string with decimal value to integer data type, the string with a fractional part should be first converted to float data type using the float() function and then to integer data type using int() function.
Converting a string or integer to float data type using float() function

The float() function converts an integer or string to floating-point values provided that the given string represents an integer value.

num_int = 5
type_float = float(num_int)
print("converting int to float: ", type_float)
print("Data type of type_float: ", type(type_float))
num_string = '123.567'
type_float = float(num_string)
print("converting string to float: ", type_float)
print("Data type of type_float : ", type(type_float))

The above code returns the output as

converting int to float:  5.0
Data type of type_float:  <class 'float'>
converting string to float:  123.567
Data type of type_float :  <class 'float'>
Converting boolean values to integer and float data type

The int() function returns 1 for True, 0 for False and float() function returns 1.0 for True, 0.0 for False.

val_T = int(True)
print("Converting True to int data type: ", val_T)
val_F = int(False)
print("Converting False to int data type: ", val_F)
val_T = float(True)
print("Converting True to float data type: ", val_T)
val_F = float(False)
print("Converting True to int data type: ", val_F)

Output

Converting True to int data type:  1
Converting False to int data type:  0
Converting True to float data type:  1.0
Converting True to int data type:  0.0
Converting a float or integer to string data type using str() function

The str() function converts the integer and floating-point values to string data type.

num_int = 5
type_str = str(num_int)
print("converting int to string: ", type_str)
print("Data type of type_str: ", type(type_str))
num_float = 23.45
type_str = str(num_float)
print("converting float to str: ", type_str)
print("Data type of type_str : ", type(type_str))

Output

converting int to string:  5
Data type of type_str:  <class 'str'>
converting float to str:  23.45
Data type of type_str :  <class 'str'>
Converting an integer to hexadecimal and octal values

The hex() function converts an integer to hexadecimal and the oct() function converts an integer to octal value. The hex() and oct() function returns the values in string data type.

Example,

num  = 9
oct_val = oct(9)
print("Conversion of int to oct: ", oct_val)
hex_val = hex(9)
print("Conversion of int to oct: ", hex_val)

Output

Conversion of int to oct:  0o11
Conversion of int to oct:  0x9
Converting an iterable to list, tuple, set, or dictionary

list() : The list() function converts a sequence(tuple, string, set, etc) to a list iterable.

tuple() : The tuple() function converts a sequence(list, string, set, etc) to a tuple iterable.

set() : The set() function converts a sequence(list, string, tuple, etc) to a set iterable.

dict() : A dict() function converts a tuple of order (key, value) to dictionary.

string_1 = 'Python'
list_1 = list(string_1)
print("Converting a string to list: ", list_1)
tuple_1 = tuple(string_1)
print("Converting a string to tuple: ", tuple_1)
set_1 = set(string_1)
print("Converting a string to set: ", set_1)
items = [(1, 'A'), (2, 'B'), (3, 'C')]
dict_1 = dict(items)
print("Converting a list of tuples to dict: ", dict_1 )

Output

Converting a string to list:  ['P', 'y', 't', 'h', 'o', 'n']
Converting a string to tuple:  ('P', 'y', 't', 'h', 'o', 'n')
Converting a string to set:  {'n', 't', 'P', 'y', 'o', 'h'}
Converting a list of tuples to dict:  {1: 'A', 2: 'B', 3: 'C'}
Converting a character to an integer using ord () and an integer to the character using chr() function

An ord() function returns the ASCII value of a character and the chr() function returns the character for an integer value.

letter = 'B'
print("The ASCII value of 'B': ", ord('B'))
integer = 89
print("The character for Integer value 89: ", chr(89))

Output

The ASCII value of 'B':  66
The character for Integer value 89:  Y
Converting a real value to a complex number

The complex() function takes two values real and imaginary values and returns a complex number.

print(complex(1, 3))
print(complex(3))
print(complex(0, 6))

Output

(1+3j)
(3+0j)
6j
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions