Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีพิมพ์ Tuple ทั้งหมดใน Python โดยใช้ String Formatting

เมื่อใช้ string formatting แบบเก่าใน Python คือ "%s" % () หากสิ่งที่อยู่หลังเครื่องหมายเปอร์เซ็นต์เป็น tuple Python จะพยายามแยกมันและส่งสมาชิกแต่ละตัวไปยังสตริง ตัวอย่างเช่น:

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

ผลลัพธ์:

TypeError: not all arguments converted during string formatting

สิ่งนี้เกิดจากเหตุผลที่กล่าวมา หากคุณต้องการส่ง tuple คุณต้องสร้าง wrapping tuple โดยใช้ไวยากรณ์ (tup,) ตัวอย่างเช่น:

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

ผลลัพธ์:

this is a tuple (1, 2, 3)

สัญลักษณ์ (tup,) แยกแยะ single-valued tuple จากนิพจน์ทั่วไป