Data Type Conversion
There are two types of type conversion. They are
1) Implicit Conversion
2) Explicit Conversion
Implicit Type Conversion
The Python is a Dynamic Programming Language. We can not define the datatype while declaring the variables. So the data conversion from one data type to another implicitly while working some arithmetic operations like addition, subtraction, multiplication, division. when the operands are in different datatypes then the implicit conversion happens.
For Example
In this example a is an integer. After adding a float number, a is convert into float. This is called Implicit Conversion.
Explicit Type Conversion
Sometimes, you may need to perform a conversion between the built-in types. To between types, you simply use the type name as a function. This is called Explicit Conversion.
These are several built-in functions to perform conversion from one data type to another. These functions return a new object representing the converted value.
int(x [, base])
Converts 'X' to an integer, base specifies the base if 'X' is a string. (base is optional)
float(x)
Converts 'x' to a floating point number.
complex(real [, imag])
Creates a complex number
str(x)
Converts object 'x' to a string representation.
repr(x)
Converts object 'x' to an expression string.
eval(str)
The eval() method parses the expression passed to this method and runs Python expression (code) within the program.
tuple(s)
Converts 's' to a tuple.
list(s)
Converts 's' to a list.
set(s)
Converts 's' to a set.
dict(d)
Creates a dictionary. 'd' must be a sequence of (key, value) tuples.
frozenset(s)
Converts 's' to a frozenset.
chr(x)
Converts an integer to a character.
ord(x)
Converts a single character to its integer.
hex(x)
Converts an integer to a hexadecimal string.
oct(x)
Converts an integer to an octal string.
Post a Comment