Python Data Type Casting – Python Programming

Python Data Type Casting - Python Programming, What are python data types and how to convert to str, int, float
Image by Free-Photos from Pixabay

Python Variable Casting means converting one data type variable into another data type variable. Casting functions return a new object representing the converted value.

Types of Casting Functions:

  • int(x): Converts an x variable into Integer from the float, integer or string (String should be a whole number) variable.
  • float(x): Converts an x variable into Float from the float, integer or string (String should be an integer or float) variable.
  • str(x): Converts an x variable into String from the float, integer or string variable.

Data Type Conversion Examples:

Converting Integer to String, Float in Python

a = 202             # Integer
x = str(a)          # Output: 202 -> String
y = int(a)          # Output: 202
z = float(a)        # Output: 202.0

Converting Float to String, Integer in Python

b = 1.25            # Float
x = str(b)          # Output: 1.25 -> String
y = int(b)          # Output: 1
z = float(b)        # Output: 1.25

Converting String to Float, Integer in Python

c = "StudyGyaan"    # String
x = str(c)          # Output: 1.25 -> String
# y = int(c)        -> Cannot convert         
# z = float(c)      -> Cannot convert

Whats Next – Python Operators

Share