🌟 Join our Telegram group for exclusive updates! Join Now Get Involved

Type Casting

Type Casting in Python

Type casting, also known as type conversion, involves changing the data type of a variable or value from one type to another. In Python, you can perform type casting explicitly using built-in functions

1. int(x[, base]):

Converts x to an integer. If x is a floating-point number, the decimal part is truncated (not rounded).

float_num = 3.14
int_num = int(float_num)  # Converts the float 3.14 to an integer (truncates to 3)

2. float(x):

Converts x to a floating-point number.

num = 42
float_num = float(num)  # Converts the integer 42 to a float (42.0)

3. str(x):

Converts x to a string.

num = 123
str_num = str(num)  # Converts the integer 123 to the string '123'

4. bool(x):

Converts x to a Boolean value. False for numeric types if the value is zero, and True otherwise. For strings, False for an empty string, and True otherwise.

num = 0
bool_value = bool(num)  # Converts the integer 0 to False

5. list(iterable):

Converts an iterable (e.g., tuple, string) to a list.

tuple_data = (1, 2, 3)
list_data = list(tuple_data)  # Converts the tuple (1, 2, 3) to a list [1, 2, 3]

6. tuple(iterable):

Converts an iterable to a tuple.

list_data = [4, 5, 6]
tuple_data = tuple(list_data)  # Converts the list [4, 5, 6] to a tuple (4, 5, 6)

7. set(iterable):

Converts an iterable to a set.

list_data = [1, 2, 3, 3]
set_data = set(list_data)  # Converts the list [1, 2, 3, 3] to a set {1, 2, 3}

8. dict(iterable):

Converts an iterable of key-value pairs to a dictionary.

tuple_data = [('a', 1), ('b', 2)]
dict_data = dict(tuple_data)  # Converts the list [('a', 1), ('b', 2)] to a dictionary {'a': 1, 'b': 2}

9. Conversion to and from Binary, Octal, and Hexadecimal:

bin(x): Converts x to a binary string.

oct(x): Converts x to an octal string.

hex(x): Converts x to a hexadecimal string.

decimal_num = 10

binary_representation = bin(decimal_num)   # '0b1010'
octal_representation = oct(decimal_num)    # '0o12'
hexadecimal_representation = hex(decimal_num)  # '0xa'

These type casting functions are useful when you need to ensure that variables are of a specific type or when you want to perform operations that require compatible types. Always be mindful of potential loss of information when converting between types.

Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Cookies Policy

We employ the use of cookies. By accessing BYTEFOXD9, you agreed to use cookies in agreement with the BYTEFOXD9's Privacy Policy.

Most interactive websites use cookies to let us retrieve the user’s details for each visit. Cookies are used by our website to enable the functionality of certain areas to make it easier for people visiting our website. Some of our affiliate/advertising partners may also use cookies.