In Python, besides int() and float(), there are several other built-in type conversion functions that allow you to convert between different data types. Here’s a concise overview of some commonly used type conversion functions:
1. str()
Converts a value to a string.
number = 100
string_number = str(number) # "100"
2. list()
Converts an iterable (like a string, tuple, or set) to a list.
tuple_data = (1, 2, 3)
list_data = list(tuple_data) # [1, 2, 3]
3. tuple()
Converts an iterable to a tuple.
list_data = [1, 2, 3]
tuple_data = tuple(list_data) # (1, 2, 3)
4. set()
Converts an iterable to a set, which removes duplicates.
list_data = [1, 2, 2, 3]
set_data = set(list_data) # {1, 2, 3}
5. dict()
Converts a sequence of key-value pairs into a dictionary.
pairs = [('a', 1), ('b', 2)]
dict_data = dict(pairs) # {'a': 1, 'b': 2}
6. bool()
Converts a value to a Boolean (True or False).
value = 0
boolean_value = bool(value) # False
Summary
These type conversion functions are useful for ensuring that data is in the correct format for operations or comparisons. They help in manipulating and processing data effectively in Python.
If you want to practice type conversions or explore more about data types, consider checking out relevant labs on LabEx! If you have any further questions, feel free to ask!
