Python Programming – Data Type Conversion

While developing a program, sometimes it is desirable to convert one data type into another. In Python, this can be accomplished very easily by making use of built-in type conversion functions. The type conversion functions result in a new object representing the converted value. A list of data type conversion functions with their respective description is given in Table 2.2.

Function Description
int(n [,base]) Converts n to an integer, base specifies the base if n is a string.
long(n [,base]) Converts n to a long integer, base specifies the base if n is a string.
float(n) Converts n to a floating-point number.
Complex ( real [,imag]) Creates a complex number.
str(n) Converts object n to a string representation.
repr(n) Converts object n to an expression string.
eval(str) Evaluates a string and returns an object.
tuple(x) Converts x to a tuple.
list(x) Converts x to a list.
set(x) Converts x to a set.
dict(d) Creates’ a dictionary, d must be a sequence of (key, value) tuples.
frozenset(x) Converts x to a frozen set.
chr(n) Converts an integer n to a character.
unichr(n) Converts an integer n to a Unicode character.
ord(c) Converts a single character c to its integer value.
hex(n) Converts an integer n to a hexadecimal string.
oct(n) Converts an integer n to an octal string.

Python Tutorial

Leave a Reply

Your email address will not be published. Required fields are marked *