Python Tutorials
Basic

Data Structure and Data Types

String

List

Tuple

Set

Dictionary

Functions / Methods

Advance

Exception Handling

Python Type Casting


Specify a Variable Data Type

There are some times you need to specify the data type on to the variable, and this can be achieve type casting.

Object-oriented programming languages, including Python, use classes to define data types.

And defining data types can be done by calling the class constructor function.

  1. int() From an integer literal, int() constructs an integer number. From a float literal (by removing all decimals) or a string literal (provided string represents a whole number), int() constructs an integer number.

  2. float() From an integer literal or string integer literal, float() constructs a float number.

  3. str() The str() constructor constructs a string from different data types, including strings, integers, and floats.


Python int() constructor

Example
number_a = int(100)
number_b = int(100.111)
number_c = int("100")

print(number_a)
print(number_b)
print(number_c)
100
100
100

In the above example, you can see by using the int() constructor we are casting integer, float, and string.


Python float() constructor

Example
number_a = float(100)
number_b = float(100.111)
number_c = float("100")
number_d = float("100.111")

print(number_a)
print(number_b)
print(number_c)
print(number_d)
100.0
100.111
100.0
100.111

Here, we cast integers, float, and strings by using the float() constructor.


Python str() constructor

Example
number_a = str(100)
number_b = str(100.111)
number_c = str("Falcon 10")

print(number_a)
print(number_b)
print(number_c)
'100'
'100.111'
'Falcon 10'

In the above example, the str() constructor is used to cast integers, floats, and strings. You will get string data type (<'class' 'str'>) if you check the data type of all variables after casting.