Lesson 15 +10 XP

Casting

Casting

Casting means changing a value from one type to another. Python offers the constructors int(), float(), and str().

int()

Builds an integer from an int, a float (truncating), or a string:

x = int(1)      # 1
y = int(2.8)    # 2
z = int("3")    # 3

A string like "3.8" fails with int():

int("3.8")  # ValueError: invalid literal

float()

Builds a float from an int, a float, or a numeric string:

x = float(1)    # 1.0
y = float(2.8)  # 2.8
z = float("3")  # 3.0
w = float("4.2")# 4.2

str()

Builds a string from almost anything:

x = str("s1")   # 's1'
y = str(2)      # '2'
z = str(3.0)    # '3.0'

Why cast?

The most common reason is printing a number next to text:

age = 36
print("I am " + str(age) + " years old.")

Without str(), adding a string and an int raises a TypeError.

TL;DR

  • int(value) makes an integer (truncates floats).
  • float(value) makes a float.
  • str(value) makes a string.
  • Cast to str before gluing numbers into text.