Type Conversion
In Python, data types are used to classify a specific type of data, determine the values you can assign to the type, and the operations you can perform on it. When performing programming tasks, sometimes you will need to apply value conversions between types to manipulate the values differently. For example, we may need to concatenate numeric values with strings or represent decimal places in numbers that started as integer values.
The types are:
int()
float()
str()
bool()
list()
tuple()
set()
dict()
Converts a numeric value or a string that represents an integer to the int data type. If the value is a decimal number, it rounds it down (removes the decimal places). If it is not numeric, it throws an error.
print(int(43.54)) # Converts the decimal to integer, removing the decimal places
Output:
43
float()
Section titled “float()”Converts an integer or a string that represents a number to a decimal number (float), useful when you need to work with fractional values.
print(float('3.14'))print(float(10))
Output:
3.1410.0
Converts any data type (integer, decimal, boolean, lists, etc.) to a string (str). It is useful for displaying messages or concatenating with other texts.
print(str(100))print(str(True))
Output:
100True
bool()
Section titled “bool()”Converts a value to True or False depending on whether it is “empty” or not. Values such as 0, "" (empty string), [] (empty list), None and False are considered False. Everything else is True.
print(bool(1))print(bool(0))print(bool('Hello'))
Output:
TrueFalseTrue
list()
Section titled “list()”Converts iterable objects (such as strings, tuples, sets) into a list.
print(list('hello') )print(list((1, 2, 3)))
Output:
['h', 'e', 'l', 'l', 'o'][1, 2, 3]
tuple()
Section titled “tuple()”Converts an iterable object into a tuple. Similar to list(), but the result is immutable (cannot be modified).
print(tuple('abc'))print(tuple([1, 2, 3]))
Output:
('a', 'b', 'c')(1, 2, 3)
Converts an iterable object into a tuple. Similar to list(), but the result is immutable (cannot be modified).
print(set([1, 2, 2, 3]))print(set('hello') )
Output:
{1, 2, 3}{'h', 'e', 'l', 'o'}
dict()
Section titled “dict()”Converts an iterable object into a tuple. Similar to list(), but the result is immutable (cannot be modified).
print(dict([('a', 1), ('b', 2)]))
Output:
{'a': 1,'b': 2}