Casting in Python


Casting or Conversion is changing the data types of any variable from one type to another.

Example:– int to float

We can explicitly convert based on requirement.

Casting in Python is therefore done using constructor functions:

  • int():- Constructs an integer number from an integer literal a float literal (by rounding down to the previous whole number) or a string literal (providing the string represent a whole whole number).

Example:-

x = int(1)         # x will be 1
y = int(2.8)       # y will be 2
z = int("3")       # z will be 3
  • float():- Constructs a float number from an integer literal a float literal or a string literal (providing the string represent a float or an integer)

Example:-

x = float(1)         # x will be 1.0
y = float(2.8)       # y will be 2.8
z = float("3")       # z will be 3.0
w = float("4.2")     # w will be 4.2
  • str():- Constructs a string from a wide variety of data types, including strings, integer literals and float literals.

Example:-

x = str(1)         # x will be '1'
y = str(2.8)       # y will be '2.8'
z = str("3")       # z will be '3'


One thought on “Casting in Python

Leave a comment