Python Type Casting

Type casting means changing a value from one data type to another. For example, the text "25" is a string, and with type casting you can turn it into the number 25 so that you can do maths with it.

Python does this with built-in functions like int(), float() and str(). You should already know the basic types, so read Python Data Types first if needed.


Implicit and explicit type conversion

There are two ways a conversion happens in Python.

  • Implicit conversion: Python changes the type by itself, when it is safe to do so.
  • Explicit conversion: You change the type yourself by calling a function. This is what we call type casting.

Implicit conversion

When you add an integer and a float, Python converts the integer to a float automatically. So no data is lost.

a = 5          # int
b = 2.5        # float
c = a + b

print(c)
print(type(c))
Output of the above program is

7.5
<class 'float'>


Type casting functions

FunctionWhat it does
int()Converts to an integer
float()Converts to a floating point number
str()Converts to a string
bool()Converts to True or False
list()Converts to a list
tuple()Converts to a tuple
set()Converts to a set
dict()Converts to a dictionary
complex()Converts to a complex number
ord() and chr()Character to number and number to character
hex(), oct(), bin()Integer to hexadecimal, octal and binary string

int() function

The int() function converts a float, or a string that has a whole number, into an integer. It does not round the number, it just cuts the decimal part. You can also give a base as the second argument.

print(int(7.9))
print(int(-7.9))
print(int("321"))
print(int("101", 2))   # binary 101 to decimal
Output of the above program is

7
-7
321
5

Note: A string that is not a whole number gives an error. int("3.5") raises ValueError: invalid literal for int() with base 10: '3.5'. Convert it to float first, like int(float("3.5")).

float() function

The float() function converts an integer or a numeric string into a float.

print(float(5))
print(float("3.14"))
print(float("2"))
Output of the above program is

5.0
3.14
2.0

str() function

The str() function converts any value into a string. It is very useful when you want to join a number with text, because Python does not do that for you.

age = 25
print("Age: " + age)
Output of the above program is

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

Convert the number with str() and the error goes away.

age = 25
print("Age: " + str(age))
print(str(3.5))
print(str([1, 2]))
Output of the above program is

Age: 25
3.5
[1, 2]

bool() function

The bool() function gives False for zero, empty strings and empty collections, and True for almost everything else.

print(bool(0))
print(bool(""))
print(bool([]))
print(bool("False"))
print(bool(5))
Output of the above program is

False
False
False
True
True

Note that bool("False") is True, because the string is not empty.

list(), tuple(), set() and dict()

These functions change one collection into another. A string is also a collection of characters.

print(list("hi"))
print(tuple([1, 2, 3]))
print(set([1, 2, 2, 3]))
print(dict([("a", 1), ("b", 2)]))
Output of the above program is

['h', 'i']
(1, 2, 3)
{1, 2, 3}
{'a': 1, 'b': 2}

When you convert a list to a set, the duplicate values are removed, and the order is not guaranteed. Also you cannot convert a single number like list(5), because a number is not iterable.

ord() and chr() functions

ord() gives the Unicode (ASCII) number of a character, and chr() does the opposite.

print(ord("a"))
print(ord("A"))
print(chr(97))
Output of the above program is

97
65
a

hex(), oct() and bin() functions

These functions take an integer and return a string that shows the number in another number system.

print(hex(31))
print(oct(31))
print(bin(5))
Output of the above program is

0x1f
0o37
0b101

complex() function

print(complex(2))
print(complex(21.3))
Output of the above program is

(2+0j)
(21.3+0j)


Type casting with user input

The input() function always returns a string. So when you ask for a number, you must convert it.

age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
Output of the above program is

Enter your age: 20
Next year you will be 21


Summary

  • Type casting means converting a value from one type to another.
  • Python converts types implicitly when it is safe, like int to float in addition.
  • Use int(), float(), str() and bool() for simple values.
  • Use list(), tuple(), set() and dict() for collections.
  • A wrong conversion, like int("abc"), raises a ValueError. Handle it with try and except.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.