Python Type Conversion
Type conversion, also known as type casting or type coercion, refers to the process of changing the data type of a variable from one type to another in Python. Python is a dynamically-typed language, which means that the data type of a variable is determined automatically at runtime. However, sometimes it is necessary to convert the data from one type to another to perform specific operations or to ensure proper functionality.
Python provides built-in functions that allow you to perform type conversion. Here are some of the commonly used type conversion functions:
int():
Used to convert a value to an integer type.
1 2 3 |
string_num = "10" integer_num = int(string_num) print(integer_num) # Output: 10 |
float():
Used to convert a value to a floating-point type.
1 2 3 |
string_num = "3.14" float_num = float(string_num) print(float_num) # Output: 3.14 |
str():
Used to convert a value to a string type.
1 2 3 |
integer_num = 42 string_num = str(integer_num) print(string_num) # Output: "42" |
bool():
Used to convert a value to a Boolean type. It returns True
for non-zero values and False
for zero values, and it also converts empty sequences (e.g., an empty string, list, or dictionary) to False
.
1 2 3 4 5 6 7 |
number = 5 boolean_value = bool(number) print(boolean_value) # Output: True empty_string = "" empty_string_bool = bool(empty_string) print(empty_string_bool) # Output: False |
list(), tuple(), set():
Used to convert a sequence (e.g., string, tuple, list) to a list, tuple, or set, respectively.
1 2 3 4 5 6 7 8 9 |
string_value = "hello" list_value = list(string_value) print(list_value) # Output: ['h', 'e', 'l', 'l', 'o'] tuple_value = tuple(list_value) print(tuple_value) # Output: ('h', 'e', 'l', 'l', 'o') set_value = set(list_value) print(set_value) # Output: {'e', 'o', 'l', 'h'} |
Keep in mind that type conversions may lead to loss of precision or unexpected results, so be cautious while performing type conversions, especially when converting between numerical types (e.g., int to float) or when dealing with non-numeric data. Always make sure that the conversion is appropriate for the data being processed.