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

ฟังก์ชัน format() ใน Python

เมธอด format() ใช้จัดรูปแบบค่าและแทรกเข้าไปใน placeholder ({}) ภายในสตริง เป็นวิธีที่ทรงพลังและยืดหยุ่นกว่าการใช้ % formatting แบบเก่า

การใช้ format() แบบพื้นฐาน (Single placeholder)

for i in range(19, 25):
    print("There are {} boxes!".format(i))

ผลลัพธ์

There are 19 boxes!
There are 20 boxes!
There are 21 boxes!
There are 22 boxes!
There are 23 boxes!
There are 24 boxes!

การใช้ format() หลายพารามิเตอร์ (Multiple placeholders)

i = 1
months = {'Jan', 'Feb', 'Mar'}
for m in months:
    print("Month no {} is {}".format(i, m))
    i += 1

ผลลัพธ์

Month no 1 is Jan
Month no 2 is Mar
Month no 3 is Feb

การใช้ Positional Index (ระบุตำแหน่งพารามิเตอร์)

สามารถระบุหมายเลขพารามิเตอร์ใน {} ได้ เช่น {0}, {1}

print("This week I'm working on {1}, {2} and {4}".format('Mon', 'Tue', 'Wed', 'Thu', 'Fri'))

ผลลัพธ์

This week I'm working on Tue, Wed and Fri

การใช้ Keyword Arguments (Named placeholders)

ใช้ชื่อพารามิเตอร์ใน format() และอ้างอิงในสตริงด้วยชื่อ

print("The 3{r}, 4{t} and 5{t} ranks are winners".format(r='rd', t='th'))

ผลลัพธ์

The 3rd, 4th and 5th ranks are winners

รูปแบบเพิ่มเติมที่น่าสนใจ

  • จัดตำแหน่ง: {:>10} (ขวา), {:<10} (ซ้าย), {:^10} (กึ่งกลาง)
  • จำนวนทศนิยม: {:.2f}
  • รูปแบบตัวเลข: {:b} (binary), {:x} (hex), {:%} (percent)
  • วันที่/เวลา: {:%Y-%m-%d}

ตัวอย่าง: print("Price: {:.2f} Baht".format(199.5)) → Price: 199.50 Baht