Conversion Methods
Core Conversion Techniques
1. Integer Conversion with int()
## Basic integer conversion
num_str = "123"
integer_value = int(num_str)
print(f"Integer: {integer_value}")
## Conversion with base specification
binary_str = "1010"
decimal_from_binary = int(binary_str, 2)
print(f"Binary to Decimal: {decimal_from_binary}")
2. Float Conversion with float()
## Standard float conversion
price_str = "19.99"
float_value = float(price_str)
print(f"Float: {float_value}")
## Scientific notation conversion
sci_notation_str = "1.23e-4"
scientific_float = float(sci_notation_str)
print(f"Scientific Float: {scientific_float}")
Conversion Method Comparison
Method |
Input Type |
Conversion Behavior |
Error Handling |
int() |
Numeric String |
Converts to integer |
Raises ValueError |
float() |
Numeric String |
Converts to floating-point |
Raises ValueError |
complex() |
Numeric String |
Converts to complex number |
Raises ValueError |
Advanced Conversion Strategies
graph TD
A[String Input] --> B{Conversion Strategy}
B --> |Safe Conversion| C[Try-Except Block]
B --> |Direct Conversion| D[Direct Method]
B --> |Custom Validation| E[Custom Conversion Function]
3. Safe Conversion Techniques
def safe_convert(value, convert_func, default=None):
try:
return convert_func(value)
except (ValueError, TypeError):
return default
## Example usage
result1 = safe_convert("123", int) ## Successful conversion
result2 = safe_convert("invalid", int, default=0) ## Fallback to default
print(f"Safe Conversion Results: {result1}, {result2}")
int()
and float()
are built-in functions with optimized performance
- Custom conversion functions add minimal overhead
- Always validate input before conversion
LabEx recommends implementing robust error handling and type checking when converting strings to numbers to ensure code reliability.