Data Conversion
Data conversion in Python involves changing the type of data from one form to another. Python provides built-in functions for type conversion, allowing you to convert data between different types. Here are some common scenarios of data conversion:
1. Implicit Type Conversion (Type Coercion):
In certain situations, Python performs automatic type conversion, also known as type coercion, to handle mixed-type operations. For example, when performing operations between integers and floats, Python converts the integer 'a' to a float to ensure compatibility.
a = 5 # int
b = 2.0 # float
result = a + b # The integer 'a' is implicitly converted to a float
2. Explicit Type Conversion (Type Casting):
You can explicitly convert data from one type to another using built-in functions. Here are some common type casting functions:
# Converts the string '123' to an integer
num_str = "123"
num_int = int(num_str)
# Converts the float 3.14 to an integer
float_num = 3.14
int_num = int(float_num)
# Converts the integer 1 to True
bool_value = bool(1)
3. Conversion Between Numeric Types:
You can convert between different numeric types using type casting.
x = 5.7
y = int(x) # Converts the float 5.7 to an integer
z = 10
w = float(z) # Converts the integer 10 to a float
4. Conversion with str()
and eval()
:
The str()
function converts an object to a string representation, and eval()
can evaluate a string as a Python expression.
# Converts the integer 42 to the string '42'
num = 42
num_str = str(num)
# Evaluates the string '3 + 5' and returns the result (8)
expr = "3 + 5"
result = eval(expr)
5. Conversion to and from Binary, Octal, and Hexadecimal:
Python provides functions like bin()
, oct()
, and hex()
for converting numbers to binary, octal, and hexadecimal representations.
decimal_num = 10
binary_representation = bin(decimal_num) # '0b1010'
octal_representation = oct(decimal_num) # '0o12'
hexadecimal_representation = hex(decimal_num) # '0xa'
Understanding data conversion is important for handling different data types in your programs and ensuring that operations are performed correctly. Always be aware of potential loss of information when converting between types, especially when converting from floating-point to integer or vice versa.