Skip to content

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.

Int.py
print(int(43.54)) # Converts the decimal to integer, removing the decimal places

Output:

Int.py
43

Converts an integer or a string that represents a number to a decimal number (float), useful when you need to work with fractional values.

Int.py
print(float('3.14'))
print(float(10))

Output:

float.py
3.14
10.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.

Str.py
print(str(100))
print(str(True))

Output:

Str.py
100
True

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.

Bool.py
print(bool(1))
print(bool(0))
print(bool('Hello'))

Output:

Bool.py
True
False
True

Converts iterable objects (such as strings, tuples, sets) into a list.

List.py
print(list('hello') )
print(list((1, 2, 3)))

Output:

List.py
['h', 'e', 'l', 'l', 'o']
[1, 2, 3]

Converts an iterable object into a tuple. Similar to list(), but the result is immutable (cannot be modified).

Tuple.py
print(tuple('abc'))
print(tuple([1, 2, 3]))

Output:

Tuple.py
('a', 'b', 'c')
(1, 2, 3)

Converts an iterable object into a tuple. Similar to list(), but the result is immutable (cannot be modified).

Set.py
print(set([1, 2, 2, 3]))
print(set('hello') )

Output:

Set.py
{1, 2, 3}
{'h', 'e', 'l', 'o'}

Converts an iterable object into a tuple. Similar to list(), but the result is immutable (cannot be modified).

Dict.py
print(dict([('a', 1), ('b', 2)]))

Output:

Dict.py
{'a': 1,
'b': 2}