Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Các phương thức chuyển đổi kiểu dữ liệu trong Python

Python cung cấp các hàm built-in chuyển đổi giữa các kiểu dữ liệu:

HàmChức năngVí dụ
int(x[, base])Chuyển sang int (base 2-36 cho string)int('11')=11, int('20', 16)=32
float(x)Chuyển sang floatfloat(11)=11.0, float('11.11')=11.11
str(x)Chuyển sang stringstr(10)='10', str([1,2])='[1, 2]'
complex(real, imag)Tạo số phứccomplex(2.5, 3.5)=(2.5+3.5j)
list(iterable)Chuyển sang listlist('abc')=['a','b','c'], list((1,2))=[1,2]
tuple(iterable)Chuyển sang tupletuple('abc')=('a','b','c'), tuple([1,2])=(1,2)
dict(iterable)Tạo dict từ cặp (k,v)dict([(1,1),(2,2)])={1:1,2:2}
set(iterable)Tạo set (unique)set([1,2,2,3])={1,2,3}
frozenset(iterable)Tạo frozenset immutablefrozenset([1,2,3])
bytes(x, enc)String → bytesbytes('abc', 'utf-8')
bool(x)Chuyển sang booleanbool(0)=False, bool([])=False

Lưu ý: int() cắt phần thập phân (truncation), không làm tròn. Dùng round() để làm tròn.