Conversion Methods in Python
Overview of Conversion Methods
Python provides multiple methods for type conversion, each serving specific use cases and data transformation needs.
Numeric Type Conversions
graph TD
A[Numeric Conversions] --> B[int()]
A --> C[float()]
A --> D[complex()]
Integer Conversion
## Integer conversion methods
string_value = "42"
integer_value = int(string_value) ## String to Integer
hex_value = int("2A", 16) ## Hexadecimal to Integer
binary_value = int("1010", 2) ## Binary to Integer
print(integer_value) ## Output: 42
print(hex_value) ## Output: 42
print(binary_value) ## Output: 10
Float Conversion
## Float conversion techniques
integer_value = 10
float_value = float(integer_value)
string_float = float("3.14")
print(float_value) ## Output: 10.0
print(string_float) ## Output: 3.14
Collection Type Conversions
Source Type |
Conversion Method |
Target Type |
Example |
Tuple |
list() |
List |
list((1,2,3)) |
List |
set() |
Set |
set([1,2,3]) |
Set |
tuple() |
Tuple |
tuple({1,2,3}) |
## Collection conversion example
original_tuple = (1, 2, 3, 4)
converted_list = list(original_tuple)
converted_set = set(original_tuple)
print(converted_list) ## Output: [1, 2, 3, 4]
print(converted_set) ## Output: {1, 2, 3, 4}
Advanced Conversion Techniques
Customized Conversion
## Custom conversion function
def custom_converter(value):
try:
return int(value)
except ValueError:
return None
## Usage example
result1 = custom_converter("123")
result2 = custom_converter("abc")
print(result1) ## Output: 123
print(result2) ## Output: None
Type Checking and Conversion
## Type checking before conversion
def safe_convert(value, target_type):
if isinstance(value, target_type):
return value
try:
return target_type(value)
except (ValueError, TypeError):
return None
## Examples
print(safe_convert("42", int)) ## Output: 42
print(safe_convert(3.14, str)) ## Output: "3.14"
print(safe_convert("hello", int)) ## Output: None
Practical Considerations
- Always handle potential conversion errors
- Use type checking before conversion
- Understand the limitations of each conversion method
LabEx recommends practicing these conversion techniques to enhance your Python programming skills.