Type conversion in Python refers to the process of converting one data type to another. Python provides built-in functions that allow you to convert between different data types.
Here are some commonly used type conversion functions in Python:
-
int(): Converts a number or a string containing a number to an integer. Example:
python num = int("10") print(num) # Output: 10 -
float(): Converts a number or a string containing a number to a floating-point number. Example:
python num = float("3.14") print(num) # Output: 3.14 -
str(): Converts an object to a string. Example:
python num = 10 str_num = str(num) print(str_num) # Output: "10" -
list(): Converts an iterable (such as a tuple or a string) to a list. Example:
python tuple_nums = (1, 2, 3) list_nums = list(tuple_nums) print(list_nums) # Output: [1, 2, 3] -
tuple(): Converts an iterable (such as a list or a string) to a tuple. Example:
python list_nums = [1, 2, 3] tuple_nums = tuple(list_nums) print(tuple_nums) # Output: (1, 2, 3) -
set(): Converts an iterable (such as a list or a string) to a set. Example:
python list_nums = [1, 2, 2, 3] set_nums = set(list_nums) print(set_nums) # Output: {1, 2, 3} -
bool(): Converts a value to a boolean. Example:
python num = 10 bool_num = bool(num) print(bool_num) # Output: True
These are just a few examples of type conversion functions in Python. There are many more functions available for specific conversions, such as ord() for converting a character to its Unicode code point, chr() for converting a Unicode code point to a character, etc.
Loading...