Python Tutorial – Conversions


Python’s Data Conversions ✈️

In Python, conversions are common operations used to change the type or format of data. Here are some common conversion techniques to help you perform data conversions in Python:
Dataint() ➜ Converts an object to an integer type.
float() ➜ Converts an object to a floating-point type.
Listlist() ➜ Converts a tuple, string, or set to a list.
tuple() ➜ Convert a tuple, string or collection to a list.
Stringstr() ➜ Convert an object to a string type.
Evaleval() ➜ Evaluates a string expression and returns the evaluated object.

Data and String Conversion

Example

"""
conversions
"""

num = input('please enter a number:')
print(type(num))
print(type(int(num)))

Result

please enter a number:101 ↩️
<class 'str'>
<class 'int'>

Example

"""
conversions
"""

num = 101
stg = '101'
print(type(float(num)))
print(float(num))
print(float(stg))
print(type(str(stg)))
print(str(stg))

Result

<class 'float'>
101.0
101.0
<class 'str'>
101

List and Eval Conversions

Example

"""
conversions
"""

lst = [100, 200, 300]
tup = (100, 200, 300)
print(type(tuple(lst)))
print(tuple(lst))
print(type(list(tup)))
print(list(tup))

str1 = '1'
str2 = '1.1'
str3 = '[100, 200, 300]'
str4 = '(100, 200, 300)'
print(type(eval(str1)))
print(type(eval(str2)))
print(type(eval(str3)))
print(type(eval(str4)))
print(eval(str1))
print(eval(str2))
print(eval(str3))
print(eval(str4))

Result

<class 'tuple'>
(100, 200, 300)
<class 'list'>
[100, 200, 300]
<class 'int'>
<class 'float'>
<class 'list'>
<class 'tuple'>
1
1.1
[100, 200, 300]
(100, 200, 300)