Type Casting in Python: Converting Data Types with Constructor Functions

Learn about type casting in Python and how to specify a variable type using constructor functions. This guide covers how to use int(), float(), and str() to convert between different data types, including integers, floats, and strings.



Type Casting in Python

Specify a Variable Type

There may be times when you want to specify a type for a variable. This can be done with casting. Python is an object-oriented language, and as such, it uses classes to define data types, including its primitive types.

Casting in Python is done using constructor functions:

  • int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
  • float() - constructs a float number from an integer literal, a float literal, or a string literal (providing the string represents a float or an integer)
  • str()- constructs a string from a wide variety of data types, including strings, integer literals, and float literals

Example

Integers:


# Casting to integers
x = int(4)
y = int(2.2)
z = int("8")
Output

4
2
8
      

Floats:


# Casting to floats
x = float(6)     # x will be 6.0
y = float(4.8)   # y will be 4.8
z = float("2")   # z will be 2.0
w = float("7.6") # w will be 7.6
    
Output

6.0
4.8
3.0
7.6
            

Strings:


# Casting to strings
x = str("a6") # x will be 'a6'
y = str(9)    # y will be '9'
z = str(6.0)  # z will be '6.0'
Output

a6
9
6.0