OPP644-“Datatype Conversion”

Converting one datatype to another is called datatype conversion. Below are the details of the same

>>> t=”dd”

>>> type(t)

<type ‘str’>

>>> int(t)   

Traceback (most recent call last):

File “<pyshell#5>”, line 1, in <module>

int(t)

ValueError: invalid literal for int() with base 10: ‘dd’

>>> t=”78″

>>> type(t)

<type ‘str’>

>>> d=int(t)

>>> type(d)

<type ‘int’>

>>> t

’78’

>>> int(t)

78

>>> float(t)

78.0

>>> complex(t)

(78+0j)

>>> repr(t)       # converts to expression string

“’78′”

>>> tuple(t)

(‘7’, ‘8’)

>>> dict(t)

Traceback (most recent call last):

File “<pyshell#52>”, line 1, in <module>

dict(t)

ValueError: dictionary update sequence element #0 has length 1; 2 is required

>>> g=4,5

>>> g

(4, 5)

>>> dict(g)

Traceback (most recent call last):

File “<pyshell#68>”, line 1, in <module>

dict(g)

TypeError: cannot convert dictionary update sequence element #0 to a sequence

>>> d

78

>>> ls = [‘a’, ‘b’]

>>> dict(ls)

Traceback (most recent call last):

File “<pyshell#87>”, line 1, in <module>

dict(ls)

ValueError: dictionary update sequence element #0 has length 1; 2 is required

>>> dict([ls])

{‘a’: ‘b’}

>>> g=5,6

>>> dict([g])

{5: 6}

NOTE :- Dictionary conversion requires a variable representing pair of two values enclosed in [] bracket as above and also there are other methods for converting the same which will discuss soon

Please click here– Nice links which explains more information on the data type conversion are :-