I. Basic Concepts of Type Conversion
Type conversion refers to the process of converting an object or piece of data from one type to another.
For example:
age = "18"
age = int(age)
print(age) # 18
print(type(age)) # <class 'int'>
The original "18" is a string, and after conversion it becomes the integer 18.
Python is a dynamically typed language; variables do not need to be declared with a fixed type in advance, but operations between different types are still constrained by type rules.
For example:
a = 10
b = "20"
# print(a + b)
# TypeError: unsupported operand type(s)
Although both a and b can be assigned to variables, you cannot directly perform ordinary addition between an integer and a string.
You first need to make the conversion rule clear:
result = a + int(b)
print(result) # 30
Type conversion in Python is mainly divided into two types:
- Explicit type conversion
- Implicit type conversion
II. Explicit Type Conversion
Explicit type conversion, also called type casting, refers to the programmer actively calling a conversion function to convert an object to the target type.
Python provides several built-in type constructors for conversion.
1. Integer Conversion: int()
int() is used to convert objects that meet the rules into integers.
print(int(10.8)) # 10
print(int(-10.8)) # -10
print(int("123")) # 123
print(int(True)) # 1
print(int(False)) # 0
Note the following:
- When a floating-point number is converted to an integer, it is truncated toward zero rather than rounded.
- A string that represents an integer can be converted to an integer.
- An invalid string will raise
ValueError. boolis a subclass ofint, so it can be converted to an integer.
print(int(3.9)) # 3
print(int(-3.9)) # -3
# print(int("3.9"))
# ValueError
If you need to convert a floating-point string to an integer, you can first convert it to a floating-point number:
value = int(float("3.9"))
print(value) # 3
2. Floating-Point Conversion: float()
float() is used to convert numbers or correctly formatted strings into floating-point numbers.
print(float(10)) # 10.0
print(float("3.14")) # 3.14
print(float(True)) # 1.0
print(float(False)) # 0.0
Floating-point numbers can also represent special values:
print(float("inf")) # inf
print(float("-inf")) # -inf
print(float("nan")) # nan
These values represent positive infinity, negative infinity, and not-a-number, respectively.
Note that floating-point numbers are usually represented using IEEE 754 double precision, which cannot precisely represent all decimal fractions.
value = 0.1 + 0.2
print(value)
# 0.30000000000000004
Therefore, when dealing with monetary amounts and precise decimal calculations, you should consider using decimal.Decimal.
3. String Conversion: str()
str() is used to convert an object into a human-readable string representation.
print(str(100)) # '100'
print(str(3.14)) # '3.14'
print(str(True)) # 'True'
print(str(None)) # 'None'
Custom objects can define their string representation through __str__():
class User:
def __init__(self, name):
self.name = name
def __str__(self):
return f"用户:{self.name}"
user = User("Alice")
print(str(user))
# User: Alice
str() and repr() are not exactly the same:
str()is more focused on readability.repr()is more focused on clearly expressing object information and is often used for debugging.
4. Boolean Conversion: bool()
bool() converts an object to a Boolean value according to the object's truth-value rules.
print(bool(1)) # True
print(bool(0)) # False
print(bool("hello")) # True
print(bool("")) # False
print(bool([1])) # True
print(bool([])) # False
print(bool(None)) # False
Common falsy values include:
FalseNone- numeric zero
- empty string
- empty list
- empty tuple
- empty dictionary
- empty set
Note in particular:
print(bool("False")) # True
print(bool("0")) # True
bool() does not parse the logical meaning in the string; it only checks whether the string is empty.
5. List conversion: list()
list() is used to convert an iterable into a list.
print(list("Python"))
# ['P', 'y', 't', 'h', 'o', 'n']
print(list((1, 2, 3)))
# [1, 2, 3]
print(list({1, 2, 3}))
# [1, 2, 3]
When converting a dictionary to a list, you get the dictionary's keys by default:
data = {
"name": "Alice",
"age": 20,
}
print(list(data))
# ['name', 'age']
If you need to get the values:
print(list(data.values()))
If you need to get key-value pairs:
print(list(data.items()))
6. Tuple conversion: tuple()
tuple() converts an iterable into a tuple.
print(tuple([1, 2, 3]))
# (1, 2, 3)
print(tuple("Python"))
# ('P', 'y', 't', 'h', 'o', 'n')
A tuple is an immutable sequence and is suitable for representing a collection of data that you do not want to be modified.
7. Set conversion: set()
set() converts an iterable into a set.
numbers = [1, 2, 2, 3, 3, 3]
result = set(numbers)
print(result)
# {1, 2, 3}
A set has two important characteristics:
- Elements are unique.
- It does not guarantee ordinary sequence-style access in insertion order.
Sets are commonly used for deduplication and set operations:
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # union
print(a & b) # intersection
print(a - b) # difference
8. Dictionary conversion: dict()
dict() is used to create dictionaries, and it can also convert an iterable of key-value pairs that meets the requirements into a dictionary.
pairs = [
("name", "Alice"),
("age", 20),
]
user = dict(pairs)
print(user)
# {'name': 'Alice', 'age': 20}
You can also create it using keyword arguments:
user = dict(name="Alice", age=20)
9. Byte conversion: bytes() and bytearray()
bytes() is used to create immutable byte sequences, and bytearray() is used to create mutable byte sequences.
text = "Python"
data = text.encode("utf-8")
print(data)
# b'Python'
print(type(data))
# <class 'bytes'>
Converting bytes to a string:
text = data.decode("utf-8")
print(text)
# Python
Creating a mutable byte sequence:
data = bytearray(b"Python")
data[0] = 74
print(data)
# bytearray(b'Jython')
Note that when encoding and decoding text, the character encoding must be specified explicitly to avoid garbled text or decoding errors.
III. Rules and Boundaries of Explicit Type Conversion
Explicit conversion does not mean that any type can be converted to any other type unconditionally.
1. Valid Conversions
print(int("123"))
print(float("3.14"))
print(str(100))
print(list((1, 2, 3)))
print(tuple([1, 2, 3]))
These conversions conform to the construction rules of the target type.
2. Invalid Conversions
# int("hello")
# ValueError
# int("3.14")
# ValueError
# float("Python")
# ValueError
Different error types need to be distinguished:
| Exception | Common Causes |
|---|---|
ValueError |
The conversion rule exists, but the specific data is invalid |
TypeError |
The object type does not support the target operation |
OverflowError |
The value exceeds the representable range of an operation or conversion |
For example:
int("abc")
The string type can participate in integer conversion, but "abc" is not a valid integer representation, so a ValueError is raised.
3. Catching Conversion Exceptions
When handling external input, invalid data should be considered:
def parse_age(value):
try:
return int(value)
except (ValueError, TypeError):
return None
print(parse_age("18")) # 18
print(parse_age("hello")) # None
print(parse_age(None)) # None
However, in real-world business code, directly returning None may obscure the cause of the conversion failure.
You can also return an explicit result:
def parse_age(value):
try:
age = int(value)
except (ValueError, TypeError):
return False, None
if age < 0:
return False, None
return True, age
success, age = parse_age("18")
If detailed error information needs to be preserved, you can also use exceptions or structured result objects.
IV. Implicit Type Conversion
Implicit type conversion means that when Python performs certain operations, it automatically handles compatibility relationships between different types according to the language rules.
Unlike explicit conversion, implicit conversion does not require the programmer to manually call functions such as int() or float().
1. Implicit Conversion from bool to int
Because bool is a subclass of int, Boolean values can participate in integer arithmetic.
a = True
b = False
print(a + 10) # 11
print(b + 10) # 10
This behavior results from Python's type inheritance relationship.
2. Operations Involving Integers and Floating-Point Numbers
When an integer and a floating-point number are used in arithmetic, the integer is usually converted to a floating-point number before the operation is performed.
a = 10
b = 2.5
result = a + b
print(result) # 12.5
print(type(result)) # <class 'float'>
Here:
ais anint.bis afloat.- The result of the operation is a
float.
This can be understood as:
result = float(a) + b
However, this is only a conceptual equivalent expression to aid understanding; it does not mean that the interpreter must implement it by explicitly calling float().
3. Complex Numbers in Numeric Operations
Integers, floating-point numbers, and complex numbers can participate in compatible numeric operations.
a = 10
b = 2.5
c = 1 + 2j
print(a + b)
# 12.5
print(a + c)
# (11+2j)
print(b + c)
# (3.5+2j)
There are certain compatibility and promotion rules among numeric types.
This is usually understood as:
bool → int → float → complex
However, this is not a conversion chain applicable to all Python operations, but rather the type promotion relationship in common numeric operations.
4. Unsupported Types Are Not Converted Automatically
Python does not automatically convert every type that appears convertible.
a = 10
b = "20"
# print(a + b)
# TypeError
When adding a string and an integer, Python does not automatically determine whether the programmer wants numeric addition or string concatenation.
This must be made explicit:
result = a + int(b)
print(result) # 30
Or:
result = str(a) + b
print(result) # 1020
5. Implicit conversion is not the same as automatically fixing errors
a = "10"
b = 20
# print(a * b)
Here, multiplying a string by an integer is legal:
print(a * b)
# 10101010101010101010
It performs string repetition, not numeric multiplication.
Python determines behavior based on operand types and operator definitions; it does not automatically guess business intent.
V. Python Numeric Type Promotion Mechanism
Numeric Type Promotion refers to converting a lower-level numeric type into a type compatible with the operation in mixed numeric-type operations.
1. Common Numeric Type Hierarchy
In ordinary built-in numeric operations, this can be understood in the following order:
bool
↓
int
↓
float
↓
complex
This is a common type promotion model; it does not mean every operation converts step by step through the entire chain.
2. bool and int
result = True + 2
print(result) # 3
print(type(result)) # <class 'int'>
When a Boolean value participates in integer operations, the result is usually an integer.
3. int and float
result = 10 + 3.5
print(result) # 13.5
print(type(result)) # <class 'float'>
The result of an operation between an integer and a floating-point number is usually a floating-point number.
4. float and complex
result = 2.5 + (1 + 3j)
print(result) # (3.5+3j)
print(type(result)) # <class 'complex'>
The result of an operation between a floating-point number and a complex number is a complex number.
5. Type promotion may introduce precision issues
Integers can represent integer values with arbitrary precision, but floating-point numbers have limited precision and range.
large_number = 10**100
print(large_number)
The integer itself can represent this value normally, but overflow may occur when converting it to a floating-point number:
# float(10**1000)
# May raise OverflowError
Therefore, type promotion does not mean precision is necessarily preserved.
Especially in scenarios involving large integers, floating-point numbers, and financial calculations, numeric range and precision should be explicitly considered.
VI. Type Conversion in Arithmetic Operations
Different operators may have different type rules.
1. Addition
print(10 + 2.5) # 12.5
print("Hello " + "Python") # Hello Python
Addition can perform both numeric addition and string concatenation.
However, it does not support adding an integer and a string directly.
2. Division
In Python, the result of ordinary division / is usually a floating-point number, even when both operands are integers.
print(10 / 2) # 5.0
print(7 / 2) # 3.5
The floor division operator //, however, returns the quotient rounded down toward negative infinity.
print(7 // 2) # 3
print(-7 // 2) # -4
The result type depends on the operands:
print(type(7 // 2)) # <class 'int'>
print(type(7.0 // 2)) # <class 'float'>
3. Modulo Operation
print(7 % 3) # 1
print(-7 % 3) # 2
Python’s modulo result follows rules that are consistent with floor division.
4. Exponentiation
print(2 ** 3) # 8
print(2 ** -1) # 0.5
print(2 ** 0.5) # 1.414...
Even when both operands are integers, a negative integer exponent may cause the result to become a floating-point number.
5. The result type of an operation does not depend only on the input types
print(type(10 + 20)) # int
print(type(10 / 2)) # float
print(type(2 ** -1)) # float
print(type(10 + 2j)) # complex
Therefore, one cannot simply assume that the output type will necessarily be the same as the input type.
VII. Comparison and Compatibility Between Different Types
Type conversion doesn't only happen in arithmetic operations—it also affects comparison operations.
1. Comparisons Between Numeric Types
Python allows comparisons between different numeric types:
print(1 == 1.0) # True
print(True == 1) # True
print(False == 0) # True
These are the comparison rules between numeric types.
Note that equal values do not mean the objects are of the same type.
print(type(True) == type(1)) # False
2. Strings and Numbers Cannot Be Compared Directly
# print("10" > 5)
# TypeError
If you need to compare them by numeric value, convert first:
print(int("10") > 5) # True
If you want to compare them according to string rules:
print("10" > "5") # False
String comparison usually follows the lexicographic order of characters, not numeric magnitude.
3. Equality Comparisons Between Different Types
Using == between different types does not necessarily raise an error:
print("10" == 10) # False
print([] == ()) # False
print(None == False) # False
Python determines the result based on the objects' equality comparison rules.
Ordering comparisons that are not supported, however, usually raise a TypeError.
VIII. Operator Overloading and Custom Type Conversion
Python allows custom classes to define type conversion and operation behavior.
This is mainly achieved through special methods.
1. int()
Controls the behavior when an object is converted to an integer.
class Score:
def __init__(self, value):
self.value = value
def __int__(self):
return int(self.value)
score = Score(95.8)
print(int(score)) # 95
2. float()
Controls the behavior when an object is converted to a floating-point number.
class Price:
def __init__(self, value):
self.value = value
def __float__(self):
return float(self.value)
price = Price("19.99")
print(float(price)) # 19.99
3. str()
Controls the behavior when an object is converted to a string.
class Product:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
product = Product("Keyboard")
print(str(product))
4. Operator Overloading
Custom classes can define operation behavior through special methods:
| Special method | Corresponding operation |
|---|---|
__add__() |
+ |
__sub__() |
- |
__mul__() |
* |
__truediv__() |
/ |
__floordiv__() |
// |
__eq__() |
== |
__lt__() |
< |
__gt__() |
> |
For example:
```python class Money: def __init__(self, amount): self.amount = amount def __add__(self, other): if not isinstance(other, Money): return NotImplemented return Money(self.amount + other.amount) def __repr__(self): return f"Money({self.amount})" a = Money(100) b = Money(50) print(a + b) # Money(150) ```Here, __add__() defines the rule for adding two Money objects.
When an operation is not supported, returning NotImplemented is a recommended design approach for operator overloading. It allows Python to try the other operand's reverse operation method, and to raise an appropriate exception when it cannot be handled.
IX. Type Conversion and Precision Issues
Type conversion may change data precision, range, or semantics.
1. Converting a Float to an Integer Truncates
print(int(3.99)) # 3
print(int(-3.99)) # -3
int() does not round; it truncates toward zero.