Python Type Conversion

What is type conversion in python?

Type conversion is common to assign a value of one type to a variable of another type.
var = "100"
# int method converts string value into integer value.
val = int(var)

# prints integer value 100 here.
print val

Some predefined type conversion methods in python

Methods Description
int(var) Converts var to an integer
long(var) Converts var to a long integer
float(var) Converts var to a float number
complex(real [,imag]) Converts into complex number.
str(var) Converts var to a string
eval(str) Evaluates and returns an object
repr(obj) Converts object into an expression string.
frozenset(obj) Converts object into a frozen set.
tuple(value) Converts value to a tuple
list(obj) Converts obj to a list.
set(obj) Converts obj to a set.
dict({key1: value1}, {key2:value2}..) Creates a dictionary with initialized items
chr(int_var) Converts int to a character
unichr(int_var) Converts int to a Unicode character
hex(int_var) Converts int to a hexadecimal string.
oct(int_var) Converts int to an octal string.

Python Type Conversion Example

#!/usr/bin/python                                                               
                                                                                
var_a = 45;                                                                     
print "string " + str(var_a);                                                   
                                                                                
var_b = "(34 + 45)";                                                            
                                                                                
var_eval_result = eval(var_b);                                                  
print("Evaluate String: %d" % var_eval_result);                                 
                                                                                
var_c = float(var_a)/float(2);                                                  
                                                                                
print("divison in float: %f" % var_c); 
Output:
$ python typte_conversion.py
string 45
Evaluate String: 79
divison in float: 22.500000

repr type conversion example

#!/usr/bin/python                                                               
                                                                                
var_b = repr(34 + 45);                                                                                                                                     
var_eval_result = eval(var_b);                                                  
print("Evaluate String: %d" % var_eval_result);  
Output:
$ python typte_conversion.py
Evaluate String: 79

Frozen set

Frozen set is just an immutable version of a Python set object. Elements of a frozen set cannot be modified at any time, remains the same after creation but elements in set can be modified.
Returns an empty frozenset if no parameters in frozenset method.
#!/usr/bin/python                                                               
                                                                                
var_b = {1, 2, 3, 6, 7};                                                        
                                                                                
var_result = frozenset(var_b);                                                  
print("frozenset is: %s" % var_result);                                         
                                                                                
print("frozenset empty is: %s" % frozenset()); 
Output:
$ python typte_conversion.py
frozenset is: frozenset([1, 2, 3, 6, 7])
frozenset empty is: frozenset([])

Type Casting float/int in python

int type casting

Type casting string format int and float value to int, resulting invalid result when type casting into int value.
#!/usr/bin/python                                                               
                                                                                
def validSalary(sal):                                                           
    try:                                                                        
       sal = int(sal);                                                          
       return 4000 <= sal <= 7000;                                              
    except ValueError as ex:                                                    
        return False;                                                           
                                                                                
print "Salary 5000 is ", validSalary('5000');                                   
print "Salary 5000.0 is ", validSalary('5000.0');    
print "Salary '' is ", validSalary('');
Output:
$ python type_conversion.py
Salary '5000' is  True
Salary '5000.0' is  False
Salary '' is  False

float type casting

#!/usr/bin/python                                                               
                                                                                
def validSalary(sal):                                                           
    try:                                                                        
       sal = float(sal);                                                        
       return 4000 <= sal <= 7000;                                              
    except ValueError as ex:                                                    
        return False;                                                           
                                                                                
print "Salary '5000' is ", validSalary('5000');                                 
print "Salary '5000.0' is ", validSalary('5000.0');                             
print "Salary '' is ", validSalary(''); 
Output:
$ python type_conversion.py
Salary '5000' is  True
Salary '5000.0' is  True
Salary '' is  False

Privacy Policy  |  Copyrightcopyright symbol2020 - All Rights Reserved.  |  Contact us   |  Report website issues in Github   |  Facebook page   |  Google+ page

Email Facebook Google LinkedIn Twitter
^