Type conversion function are built in Python functions which are used to convert values from one type to an other. The built-in type conversion functions are:
Example 1 Convert string values to integer values '20', '40', '42.323', 'This is my first program!'.
Function | Function description |
---|---|
int(x [,base]) |
Converts an argument (x) to an integer. The base is specified if x is a string. |
float(x) |
The float function converts x to a floating point number. |
long(x, [,base]) |
The long function converts argument x to a long integer Base specifies the base if and argument is a string. |
complex(real [,imag]) |
Creates a complex number |
str(x) |
Converts argument \(x\) to string. |
repr(x) |
Converts object x to an expression strng. |
eval(x) |
The function evaluates a string and returns an object. |
tuple(x) |
Converts argument \(x\) to a tuple. |
set(x) |
Converts argument \(x\) to a set. |
dict(x) |
Converts argument \(x\) to dictionary. |
frozenset(x) |
Converts x to a frozen set (makes them immutable). |
chr(x) |
Converts an argument x (integer) to a character. |
unichr(x) |
Converts an integer (argument x) to a Unicode character. |
ord(x) |
Converts a single character to its integer value. |
hex(x) |
Converts integer to a hexidecimal string. |
oct(x) |
Converts an integer to an octal string. |
print("int(20) = {}".format(int(20)))Runing the previous code will generat the following result.
print("int(40) = {}".format(int(40)))
print("int(42.323) = {}".format(int(42.323)))
print("int(This is my first program!) = {}".format(int('This is my first program!')))
int(20) = 20Example 2 Create a program that will take user input (integer only) and convert it to float, long, complex, str, repr, tuple, chr, unichr, hex and oct.
int(40) = 40
int(42.323) = 42
ValueError: invalid literal for int() with base 10: 'This is my first program!'
USER_INPUT = int(input("Enter an integer: "))
print("float(USER_INPUT) = {}".format(float(USER_INPUT)))
print("type(float(USER_INPUT)) = {}".format(type(float(USER_INPUT))))
print("complex(USER_INPUT) = {}".format(complex(USER_INPUT)))
print("type(complex(USER_INPUT)) = {}".format(type(complex(USER_INPUT))))
print("str(USER_INPUT) = {}".format(str(USER_INPUT)))
print("type(str(USER_INPUT)) = {}".format(type(str(USER_INPUT))))
print("repr(USER_INPUT) = {}".format(repr(USER_INPUT)))
print("type(repr(USER_INPUT)) = {}".format(type(repr(USER_INPUT))))
print("chr(USER_INPUT) = {}".format(chr(USER_INPUT)))
print("type(chr(USER_INPUT)) = {}".format(type(chr(USER_INPUT))))
print("hex(USER_INPUT) = {}".format(hex(USER_INPUT)))
print("type(hex(USER_INPUT)) = {}".format(type(hex(USER_INPUT))))
print("oct(USER_INPUT) = {}".format(oct(USER_INPUT)))
print("type(oct(USER_INPUT) = {}".format(type(oct(USER_INPUT))))
print("hex(USER_INPUT) = {}".format(hex(USER_INPUT)))
print("type(hex(USER_INPUT)) = {}".format(type(hex(USER_INPUT))))