Ticker

6/recent/ticker-posts

Python: Type Casting

We can convert one type of value to another type. This conversion is called Typecasting or Type conversion. The following are various inbuilt functions for type casting. 

  1. int() 
  2. float() 
  3. complex() 
  4. bool() 
  5. str()

1.int(): 

We can use this function to convert values from other types to int 

Eg: 

>>> int(123.987) 
 123 
>>> int(10+5j) 
 TypeError: can't convert complex to int 
>>> int(True) 
 1 
>>> int(False) 
 0 
>>> int("10") 
 10 
>>> int("10.5") 
 ValueError: invalid literal for int() with base 10: '10.5' 
>>> int("ten") 
 ValueError: invalid literal for int() with base 10: 'ten' 
>>> int("0B1111") 
 ValueError: invalid literal for int() with base 10: '0B1111' 

2. float():

We can use float() function to convert other type values to float type.

1) >>> float(10) 
2) 10.0 
3) >>> float(10+5j) 
4) TypeError: can't convert complex to float 
5) >>> float(True) 
6) 1.0 
7) >>> float(False) 
8) 0.0 
9) >>> float("10") 
10) 10.0 
11) >>> float("10.5") 
12) 10.5 
13) >>> float("ten") 
14) ValueError: could not convert string to float: 'ten' 
15) >>> float("0B1111") 
16) ValueError: could not convert string to float: '0B1111'

3.complex():

We can use complex() function to convert other types to complex type.

Form-1: complex(x)

We can use this function to convert x into complex number with real part x and imaginary part 0.

Eg: 

1) complex(10)==>10+0j 
2) complex(10.5)===>10.5+0j 
3) complex(True)==>1+0j 
4) complex(False)==>0j 
5) complex("10")==>10+0j 
6) complex("10.5")==>10.5+0j 
7) complex("ten") 
8) ValueError: complex() arg is a malformed string 

Form-2: complex(x,y)

We can use this method to convert x and y into complex number such that x will be real part and y will be imaginary part.

Eg: complex(10,-2)==>10-2j
 complex(True,False)==>1+0j

4. bool():

We can use this function to convert other type values to bool type.

Eg: 

1) bool(0)==>False 
2) bool(1)==>True 
3) bool(10)===>True 
4) bool(10.5)===>True 
5) bool(0.178)==>True 
6) bool(0.0)==>False 
7) bool(10-2j)==>True 
8) bool(0+1.5j)==>True 
9) bool(0+0j)==>False 
10) bool("True")==>True 
11) bool("False")==>True 
12) bool("")==>False

5. str():

We can use this method to convert other type values to str type

Eg:

1) >>> str(10) 
2) '10' 
3) >>> str(10.5) 
4) '10.5' 
5) >>> str(10+5j) 
6) '(10+5j)' 
7) >>> str(True) 
8) 'True'

"List Type Casting In Python"

"Python Type Casting Custom Class"

"Type Casting In Python Example"

"Implicit Type Casting In Python"

"Type Casting In Python W3schools"

"Explicit Type Conversion In Python"