Skip to main content

Python Casting

Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types. Casting is when you convert a variable value from one type to another. Python allows you to cast various data types into one another. This also allows you to specify a data type to a variable. This is called Python Casting.

This is done using constructor functions:

  • int(): It constructs an integer number from an integer literal, a float literal, or a string literal.
  • float(): It constructs a float number from an integer literal, a float literal or a string literal.
  • str(): It constructs a string from a wide variety of data types, including strings, integer literals and float literals.

It is a method used to change the variables/ values declared in a certain data type into a different data type to match the operation required to be performed by the code snippet. In python, this feature can be accomplished by using constructor functions like int(), string(), float(), etc. 

Example:

a = int(5)
b = int("3")
x = float(9)     
y = float(2.8)   

print(a)
print(b)
print(x)
print(y)

Output:

5
3
9.0
2.8
Tags
Submitted by devanshi.srivastava on June 30, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.