Practical String Conversion
String Conversion Fundamentals
String conversion is a critical skill in Python for transforming objects into string representations across various contexts.
Built-in Conversion Functions
## Basic conversion methods
print(str(42)) ## Converts integer to string
print(repr([1, 2, 3])) ## Detailed list representation
print(format(3.14159, '.2f')) ## Formatted float conversion
Conversion Workflow
graph TD
A[Original Object] --> B{Conversion Method}
B --> C[str()]
B --> D[repr()]
B --> E[format()]
C --> F[User-Friendly String]
D --> G[Technical String Representation]
E --> H[Formatted String Output]
Conversion Method Comparison
Method |
Purpose |
Example |
Output |
str() |
Simple conversion |
str(123) |
"123" |
repr() |
Detailed representation |
repr([1,2]) |
"[1, 2]" |
format() |
Formatted conversion |
format(3.14, '.2f') |
"3.14" |
Advanced Conversion Techniques
class ConvertibleObject:
def __init__(self, value):
self.value = value
def __str__(self):
return f"Value: {self.value}"
def __repr__(self):
return f"ConvertibleObject(value={self.value})"
## Conversion demonstration
obj = ConvertibleObject(42)
print(str(obj)) ## Uses __str__ method
print(repr(obj)) ## Uses __repr__ method
Type-Specific Conversions
## Handling different data types
def smart_convert(obj):
try:
return str(obj)
except ValueError:
return repr(obj)
## Example conversions
print(smart_convert(123)) ## String of integer
print(smart_convert([1, 2, 3])) ## List representation
print(smart_convert({"key": 1})) ## Dictionary representation
Conversion Error Handling
class CustomConverter:
def __init__(self, data):
self.data = data
def __str__(self):
try:
return f"Converted: {self.data}"
except Exception as e:
return f"Conversion Error: {e}"
Best Practices
- Always implement
__str__()
and __repr__()
for custom classes
- Use appropriate conversion methods based on context
- Handle potential conversion errors gracefully
Note: LabEx encourages practicing these conversion techniques to become proficient in Python string manipulation.