Python Tutorial
var = "100" # int method converts string value into integer value. val = int(var) # prints integer value 100 here. print val
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. |
#!/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
#!/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
#!/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([])
#!/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
#!/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
Python Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us | Report website issues in Github | Facebook page | Google+ page