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

In tuple hoàn chỉnh trong Python dùng string formatting

Dùng old-style formatting "%s" % (tuple), Python sẽ unpack tuple. Muốn in cả tuple, bọc thêm tuple: (tup,).

Sai

tup = (1,2,3)
print("this is a tuple %s" % (tup))  # TypeError

Đúng

tup = (1,2,3)
print("this is a tuple %s" % (tup,))

Kết quả: this is a tuple (1, 2, 3)

(tup,) tạo single-element tuple chứa tuple gốc, tránh unpack.