Computer >> Computer tutorials >  >> Programming >> Python

What are different data conversion methods in Python?


Numeric data conversion functions −

int() − converts a floating point number or a string with integer representation to integer object. When converting a string, parameter of base of number system to convert hexadecimal or octal number to integer

>>> int('11')
11
>>> int(11.15)
11
>>> int('20', 8)
16
>>> int('20', 16)
32

float() − attaches fractional part with 0 to integer, or converts a string with float representation to a floating point number object.

>>> float(11)
11.0
>>> float('11.11')
11.11

str() − converts object of any data type to string representation

>>> str(10) # int to str
'10'
>>> str(11.11) # float to str
'11.11'
>>> str([1,2,3]) #list to str
'[1, 2, 3]'
>>> str((1,2,3)) # tuple to str
'(1, 2, 3)'
>>> str({1:100,2:200})
'{1: 100, 2: 200}'

complex() − accepts two floats as parameters and returns a complex number object. First parameter is the real component and second parameter multiplied by j is the imaginary component.

>>> complex(2.5, 3.5)
(2.5+3.5j)

list() − converts a string and tuple to list object. It also returns a list object from keys of a dictionary

>>> list("TutorialsPoint")
['T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't']
>>> list((1,2,3))
[1, 2, 3]
>>> list({'a':11,'b':22,'c':33})
['a', 'b', 'c']

tuple() − converts a string and list to tuple object. It also returns a tuple object from dictionary keys

>>> tuple('TutorialsPoint')
('T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's', 'P', 'o', 'i', 'n', 't')
>>> tuple([1,2,3])
(1, 2, 3)
>>> tuple({'a':11,'b':22,'c':33})
('a', 'b', 'c')

dict() − returns a dictionary object from list of two tuples with equal number of elements.

>>> dict([(1,1),(2,2)])
{1: 1, 2: 2}