Python Type Conversion
1. Implicit Type Conversion (Type Coercion)
integer_value = 10 # int
float_value = 3.5 # float
result = integer_value + float_value # int + float → float
print(result) # Output: 13.5
print(type(result)) # Output: <class 'float'>Python automatically promotes int to float in mixed numeric expressions.
2. Explicit Type Conversion to Integer (int())
float_value = 9.99
string_value = "42"
int_from_float = int(float_value)
int_from_string = int(string_value)
print(int_from_float) # Output: 9 (fraction truncated)
print(int_from_string) # Output: 42Use int() to convert compatible values to integers. Fractions are truncated, not rounded.
3. Explicit Type Conversion to Float (float())
float() converts integers and numeric strings to floating-point numbers.
4. Explicit Type Conversion to String (str())
str() provides a readable string representation of most Python objects.
5. Converting to Boolean (bool())
By convention, “empty” values are False and non-empty values are True.
6. Converting Between Strings and Lists
list() splits a string into characters; "separator".join() combines a list of strings.
7. Converting Between Tuples, Lists, and Sets
Collection types can be converted between each other as long as the elements are compatible.
8. Converting to Dictionary (dict())
dict() can convert an iterable of key–value pairs into a dictionary.
9. Handling Conversion Errors with try / except
Invalid conversions raise exceptions (e.g., ValueError) that can be handled gracefully.
10. Custom Type Conversion via __str__ and __int__
Custom classes can define how they convert to built-in types by implementing special methods like __str__ and __int__.
Last updated