Skip to main content

Introduction to Python Casting

Python Casting

Python Casting refers to the process of explicitly converting one data type to another.

Python provides built-in functions that allow you to perform casting operations.

Here are the commonly used casting functions:

  • int(): Converts a value to an integer type.
x = 5.7
x_int = int(x)
print(x_int) # Output: 5
  • float(): Converts a value to a floating-point number type.
x = 5
x_float = float(x)
print(x_float) # Output: 5.0
  • str(): Converts a value to a string type.
x = 10
x_str = str(x)
print(x_str) # Output: "10"
  • bool(): Converts a value to a boolean type.
x = 0
x_bool = bool(x)
print(x_bool) # Output: False
  • list(), tuple(), set(), dict(): These functions are used to convert values to list, tuple, set, and dictionary types, respectively.
x = "hello"
x_list = list(x)
x_tuple = tuple(x)
x_set = set(x)
x_dict = dict(x)
print(x_list) # Output: ['h', 'e', 'l', 'l', 'o']
print(x_tuple) # Output: ('h', 'e', 'l', 'l', 'o')
print(x_set) # Output: {'e', 'l', 'o', 'h'}
print(x_dict) # Output: {'h': 'e', 'l': 'o'}
danger

Not all casting operations are possible or meaningful. For example, attempting to convert a string that doesn't represent a valid number to an integer or float will result in a ValueError.