Type Conversion in Python
Data type are of different types like integer,string,float etc.
Type conversion means converting one data type to another data type.
To convert between types, use the name of a function.
Built-in functions which performs type conversion
Function | Description | Examples |
---|---|---|
int(a, base) | It converts any data type to integer | >>> int('1111',2) 15 >>> int('1111',8) 585 |
float() | It converts string or a number data type to floating point number, provided that string consists of a number. float() argument cannot be a tuple, list, dict, set, etc. | >>> float('200.6') 200.6 >>> float(2006) 2006.0 >>> float((200,500.6)) Traceback (most recent call last): File " float((200,500.6)) TypeError: float() argument must be a string or a number, not 'tuple' >>> float('a') Traceback (most recent call last): File " float('a') ValueError: could not convert string to float: 'a' >>> float('2') 2.0 |
ord() | Return the integer ordinal of a one-character string | >>> ord('A') 65 >>> ord('a') 97 |
complex(real,imag) | It creates a complex number | >>> complex(5,6) (5+6j) |
str() | It converts data type to string | >>> str(219) '219' >>> str(2.2) '2.2' |
repr(x) | It converts an object x to an expression string | >>> repr(45) '45' >>> >>> repr(4+5) '9' |
eval(str) | Evaluates string and returns an object | >>> eval('9-6') 3 >>> eval('9+3') 12 >>> eval('9*9') 81 |
hex() | Converts integer to hexadecimal string | >>> hex(10) '0xa' >>> hex(50) '0x32' |
oct() | Converts integer to octal string | >>> oct(10) '0o12' >>> oct(50) '0o62' |
tuple() | Converts sequences like list, string, set and dictionary to tuple | >>> tuple('123') ('1', '2', '3') >>> tuple([1,2,3,45]) (1, 2, 3, 45) >>> tuple({1,2,3}) (1, 2, 3) >>> tuple({1:'i',2:'am',3:'itvoyagers'}) (1, 2, 3) |
set() | Converts sequences like list, string, tuple and dictionary to set | >>> set('123') {'1', '2', '3'} >>> set([1,2,3,45]) {1, 2, 3, 45} >>> set((1,2,3)) {1, 2, 3} >>> set({1:'i',2:'am',3:'itvoyagers'}) {1, 2, 3} >>> |
list() | Converts sequences like set, string, tuple and dictionary to list | >>> list('123') ['1', '2', '3'] >>> list({1,2,3,45}) [1, 2, 3, 45] >>> list((1,2,3)) [1, 2, 3] >>> list({1:'i',2:'am',3:'itvoyagers'}) [1, 2, 3] |
dict() | Converts list of tuples or tuple of lists to dictionary | >>> dict(((1,'hi'),(2,'bye'))) {1: 'hi', 2: 'bye'} >>> dict(([1,'hi'],[2,'bye'])) {1: 'hi', 2: 'bye'} >>> dict([(1,'hi'),(2,'bye')]) {1: 'hi', 2: 'bye'} |
chr(x) | Converts integer to a character | >>> chr(65) 'A' >>> chr(50) '2' >>> chr(97) 'a' |
For other python basics related posts:
For other advanced python related posts: