Python hỗ trợ chuyển đổi rõ ràng (explicit) giữa các kiểu dữ liệu built-in.
1. String → Numeric
s = '56'
print(int(s)) # 56 (base 10)
print(int(s, 16)) # 86 (hex)
print(int(s, 12)) # 66 (base 12)
s = '25.897'
print(float(s)) # 25.897
2. Ký tự ↔ ASCII / Cơ số
print(ord('G')) # 71
print(chr(71)) # G
print(hex(254)) # 0xfe
print(oct(62)) # 0o76
print(bin(56)) # 0b111000
# Format không prefix
print(format(254, 'x')) # fe
print(format(62, 'o')) # 76
print(format(56, 'b')) # 111000
3. Chuyển đổi Container
my_list = [10, 20, 30, 40, 50]
my_set = {10, 10, 20, 30, 20, 50, 20}
print(tuple(my_list)) # (10, 20, 30, 40, 50)
print(set(my_list)) # {40, 10, 50, 20, 30}
print(list(my_set)) # [10, 20, 50, 30] (thứ tự không đảm bảo)
4. Complex Number
c = complex(10, 5) # 10+5j
print(c.real) # 10.0
print(c.imag) # 5.0
print(complex('3+4j')) # 3+4j (từ string)
5. Tuple → Dict
tuples = (('Tiger', 4), ('Cat', 6), ('Dog', 8), ('Elephant', 10))
d = dict(tuples)
print(d) # {'Tiger':4, 'Cat':6, 'Dog':8, 'Elephant':10}
6. Ép kiểu ngầm (Implicit) – Python KHÔNG hỗ trợ
"5" + 3 # TypeError: must be str, not int
"5" + str(3) # OK: "53"
Tóm tắt hàm chuyển đổi
| Hàm | Chuyển từ | Sang |
|---|---|---|
| int(x, base) | str, float, bool | int |
| float(x) | str, int | float |
| str(x) | bất kỳ | str |
| bool(x) | bất kỳ | bool |
| list/tuple/set(x) | iterable | container |
| dict(x) | iterable of pairs | dict |
| complex(r, i) | int, float, str | complex |