Casting in Python

Lesson#11

Casting is used in Python to specify data type of a variable or convert data of one data type to another.

Being object-oriented programming language, Python uses classes to define data types. Casting is performed using constructor functions of these classes. These constructors are

  • int() — constructs an integer number
  • float() — constructs a float number f
  • str() — constructs a string

Examples:

# int examples
x = int(11) # value of x is 11
y = int(10.5) # value of y is 10
z = int("44") # value of z is 44

# float examples
x = float(12) # 12.0
y = float(3.9) # 3.9
z = float("5.8") # 5.8

# str examples
x = str("orange") # value of x is 'orange'
y = str(20) # value of y is '20'
z = str(14.5) # value of z is '14.5'

--

--