Python Cast Data Types
Python Cast Data Types
https://samatrix.io (https://samatrix.io)
In Python, we use data types to classify the type of the data for example int , float , str etc.
However in programming, we need to convert the data type between different data type
Python does not support implicit conversion excet int to float
So we need to cast data types
Integer to Float
There are instances when you need to convert int type to float type. Even though python implicitly
converts int to float . However, sometimes it is required to convert int to float manually or float to
int
In [1]: a=56
float(a) # Converts int to float by addition decimal point
Out[1]: 56.0
56.0
Float to Integer
In [2]: int(45000.789)
Out[2]: 45000
The float can be assigned to a variable and then converted into integer
In [6]: a = 45.789
int(a)
Out[6]: 45
Python does not round the float when converting the float to int. It just cutoff the values after decimal
In [7]: 4/2
Out[7]: 2.0
In [4]: 5/2
Out[4]: 2.5
In [9]: 5//2
Out[9]: 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-c11b81a42b78> in <module>
----> 1 2+' Python' # Concatenation of Number with string gives error
In [8]: a=str(2)
type(a)
Out[8]: str
In [3]: s = 2
print(str(s) + 'nd Python')
2nd Python
In [20]: str(56.897)
Out[20]: '56.897'
In [5]: sr='234'
int(sr)
Out[5]: 234
In [6]: st='234j'
int(st)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-6a6a2aec2236> in <module>
1 st='234j'
----> 2 int(st)
In [21]: a = 56.897
print('I have '+str(a)+' points')
String to Number
In programming, on various ocassion, we need to convert the string values to numbers
For example the mathematical operations on strings need conversion to numbers (integer or float)
We use int() or float() methods to convert string to number
In [15]: var1='123.45'
float(var1)
Out[15]: 123.45
In [3]: var='hell0123456'
float(var)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-3-86843a3fe513> in <module>
1 var='hell0123456'
----> 2 float(var)
In [24]: a = '58'
b = '50'
a+b
int(a) + int(b)
c = int(a) - int(b)
c
Out[24]: 8
In [8]: a=67
b=30.90
int(a+b)
Out[8]: 97
In [25]: float('78.98')
Out[25]: 78.98
In [26]: a = '89.76'
b = '78.67'
c = float(a) - float(b)
c
Out[26]: 11.090000000000003
Thank You