Giới thiệu về các kiểu dữ liệu Python và cách thực hiện chuyển đổi kiểu (type conversion).
Các kiểu dữ liệu Python
Khi tạo biến trong Python, biến có thể giữ nhiều kiểu dữ liệu khác nhau.
Python có các built-in data types sau:
- str (chuỗi)
- int, float, complex (số)
- list, tuple (chuỗi序列)
- dict (từ điển)
- set (tập hợp)
- bool (boolean)
- byte, bytearray (nhị phân)
Kiểu văn bản: str
Dùng str để khai báo biến chuỗi.
x = "some string"
y = str("another string")
Kiểu số: int, float, complex
# int
a = 5
b = int(5)
# float
c = 5.5
d = float(5.5)
# complex
e = 1j
f = complex(1j)
Kiểu sequence: list, tuple
list: collection có thứ tự, có thể thay đổi, cho phép trùng lặp.tuple: collection có thứ tự, không thể thay đổi (immutable), cho phép trùng lặp.
# list
colors = ['red', 'green', 'blue']
colors_list = list(('red', 'green', 'blue'))
# tuple
fruits = ('apple', 'orange', 'banana')
fruits_tuple = tuple(('apple', 'orange', 'banana'))
Kiểu mapping: dict
Dictionary: collection không có thứ tự, có thể thay đổi, được index bằng key-value pairs.
people = {"name": "John", "age": "45"}
people_dict = dict(name="John", age=45)
Kiểu set
Set: collection không có thứ tự, không được index.
status_codes = {"200", "300", "400", "500"}
status_codes = set(("200", "300", "400", "500"))
Kiểu boolean: bool
is_valid = False
valid = bool(is_valid)
Kiểu nhị phân: byte, bytearray
# bytes
a = b"some_text"
b = bytes(5)
# bytearray
c = bytearray(3)
Cách lấy kiểu của biến
Dùng hàm type() bao quanh biến.
colors = ['red', 'green', 'blue']
colors_list = list(('red', 'green', 'blue'))
print(type(colors_list))
print(colors_list)
fruits = ('apple', 'orange', 'banana')
fruits_tuple = tuple(('apple', 'orange', 'banana'))
print(type(fruits_tuple))
print(fruits_tuple)
Kết quả:
<class 'list'> ['red', 'green', 'blue']
<class 'tuple'> ('apple', 'orange', 'banana')
Python Data Type Conversion
Python định nghĩa các hàm chuyển đổi kiểu trực tiếp.
int sang float
x = 5
y = float(x)
print(y) # 5.0
float sang int
x = 5.0
y = int(x)
print(y) # 5
string sang list
s = "devqa"
t = list(s)
print(t) # ['d', 'e', 'v', 'q', 'a']
string sang tuple
s = "devqa"
t = tuple(s)
print(t) # ('d', 'e', 'v', 'q', 'a')
string sang set
s = "devqa"
t = set(s)
print(t) # {'d', 'e', 'a', 'v', 'q'}