Thursday, November 24, 2016

Type Conversion in Python

How to switch data types in python: Type Conversion

The type conversion method is very much at per with other programming language in python. You just have to write the type you want to convert to. Below are the example  -

>>> a=5  # An integer
>>> a=float(a)
>>> a
5.0
>>> a+5
10.0 #A float from integer and float addition, in fact you will get all the values from float to int as float
>>  a=int(a) #to convert back again to int
>>> a=str(a) #Converting to str
>>> a
'5.0 ' #Converted the float to character or string
>>>  a*5 #concatenate the string five times
 '5.05.05.05.05.0'
>>> a=int(a)
Traceback (most recent call last):
  File "<pyshell#41>", line 1, in <module>
    a=int(a)
ValueError: invalid literal for int() with base 10: '5.0'


>>> a= float(a)
>>>a 
>>> 5.0 #back to float but can convert directly to int 
>>> a=int(a)
5 # Systematic conversion - from str to float to int, so bear in mind that sometimes the conversion pattern depends on the value you are converting.

Now an interesting part, we can always convert the immutable tuple to mutable list in simple way, just like float to integer and vice-versa.
>>> a= (2,3,4,5)
>>> a=list(a)
>>> a
[2,3,4,5]

And in a smae way -
>>> a=tuple(a)
>>> a
(2,3,4,5)

Python Joke:
#Convert me to anything but my soul remain the same..

No comments:

Post a Comment

Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...