Type Conversion Skills
Basic Type Conversion Methods
Numeric Conversions
## Integer conversions
x = int(10.5) ## Truncates float to integer
y = float(42) ## Converts integer to float
z = complex(3) ## Converts to complex number
print(x) ## 10
print(y) ## 42.0
print(z) ## (3+0j)
String Conversions
## String to numeric conversions
num_str = "123"
num_int = int(num_str)
num_float = float(num_str)
print(num_int) ## 123
print(num_float) ## 123.0
Advanced Conversion Techniques
Safe Conversion Methods
def safe_convert(value, target_type):
try:
return target_type(value)
except ValueError:
return None
## LabEx safe conversion example
print(safe_convert("42", int)) ## 42
print(safe_convert("3.14", float)) ## 3.14
print(safe_convert("hello", int)) ## None
Conversion Flow Chart
graph TD
A[Input Value] --> B{Conversion Type}
B --> |To Integer| C[int()]
B --> |To Float| D[float()]
B --> |To String| E[str()]
B --> |To List| F[list()]
B --> |To Tuple| G[tuple()]
B --> |To Set| H[set()]
Comprehensive Conversion Methods
Source Type |
Conversion Function |
Example |
String to Int |
int() |
int("123") |
String to Float |
float() |
float("3.14") |
List to Tuple |
tuple() |
tuple([1,2,3]) |
Tuple to Set |
set() |
set((1,2,3)) |
Complex Conversion Scenarios
## Multi-step conversions
def advanced_conversion(data):
## Convert mixed data types
converted = []
for item in data:
if isinstance(item, str):
try:
converted.append(int(item))
except ValueError:
converted.append(item)
else:
converted.append(item)
return converted
## LabEx conversion example
mixed_data = [1, "2", "three", 4.0]
result = advanced_conversion(mixed_data)
print(result) ## [1, 2, 'three', 4.0]
Type Conversion with Error Handling
def robust_converter(value, types):
for type_func in types:
try:
return type_func(value)
except (ValueError, TypeError):
continue
return None
## Multiple type conversion attempts
conversion_types = [int, float, str]
print(robust_converter("42", conversion_types)) ## 42
print(robust_converter("3.14", conversion_types)) ## 3.14
Best Practices
- Always use try-except for safe conversions
- Understand potential data loss in conversions
- Validate input before conversion
- Use appropriate conversion methods
- Handle edge cases in LabEx projects
import timeit
## Comparing conversion methods
def method1():
return int("123")
def method2():
return float("123.45")
print(timeit.timeit(method1, number=10000))
print(timeit.timeit(method2, number=10000))
By mastering these type conversion skills, you'll write more flexible and robust Python code in your LabEx programming projects.