Typecasting or Casting in Python

In Python, type casting refers to the conversion of a value of one data type into another data type. There are several built-in functions that can be used for type casting, including int(), float(), str(), bool(), and list(), among others.

Here are some examples of type casting in Python:

  1. Converting a string to an integer:
age_str = "25"
age_int = int(age_str)
print(age_int)  # Output: 25
  1. Converting a float to an integer:
price_float = 4.99
price_int = int(price_float)
print(price_int)  # Output: 4
  1. Converting an integer to a string:
age_int = 25
age_str = str(age_int)
print(age_str)  # Output: "25"
  1. Converting a boolean to an integer:
is_true = True
is_false = False
int_true = int(is_true)
int_false = int(is_false)
print(int_true)  # Output: 1
print(int_false)  # Output: 0
  1. Converting a list to a string:
fruits = ["apple", "banana", "cherry"]
fruits_str = str(fruits)
print(fruits_str)  # Output: "['apple', 'banana', 'cherry']"

Note that not all type casting operations are possible or make sense. For example, you cannot convert a string that contains non-numeric characters to an integer using int(). In such cases, a ValueError will be raised. Similarly, you cannot convert a string that does not represent a valid float to a float using float().

Leave a Comment