จัดรูปแบบสตริงด้วย f-string ใน Python
f-strings ใส่ตัวแปรและนิพจน์ลงในข้อความได้เลย และ format specifier หลังเครื่องหมายโคลอนจะควบคุมจำนวนทศนิยม ความกว้าง การจัดแนว และตัวคั่น
จัดรูปแบบสตริงด้วย f-string ใน Python คืออะไร?
f-strings ใส่ตัวแปรและนิพจน์ลงในข้อความได้เลย และ format specifier หลังเครื่องหมายโคลอนจะควบคุมจำนวนทศนิยม ความกว้าง การจัดแนว และตัวคั่น
สร้างข้อความให้อ่านง่ายด้วย f-strings และ format specifiers ของ Python
ควรใช้เมื่อใด?
- เรียนรู้ไวยากรณ์ Python ผ่านโค้ดที่รันได้
- สร้างพื้นฐานสำหรับโจทย์ที่ซับซ้อนขึ้น
- ทดลองแนวคิดโดยไม่ต้องติดตั้งบนเครื่อง
โค้ดตัวอย่าง
name = "Lin"
score = 92.456
items = 3
# f-strings put expressions inside {} directly in the text.
print(f"{name} scored {score} points")
# Format specifiers after a colon control how values look.
print(f"Rounded: {score:.1f}")
print(f"Price: ${19.5:.2f}")
print(f"Padded: [{items:>5}] [{items:<5}] [{items:^5}]")
print(f"Thousands: {1234567:,}")
print(f"Percent: {0.875:.0%}")
# Any expression works, including calls and arithmetic.
print(f"{name.upper()} has {items * 2} tickets")
# A table with aligned columns.
for product, price in [("Tea", 2.5), ("Coffee", 3.75)]:
print(f"{product:<8}{price:>6.2f}")
ผลลัพธ์ที่คาดหวัง
Lin scored 92.456 points
Rounded: 92.5
Price: $19.50
Padded: [ 3] [3 ] [ 3 ]
Thousands: 1,234,567
Percent: 88%
LIN has 6 tickets
Tea 2.50
Coffee 3.75
หลักการทำงาน
.1f ปัดเป็นทศนิยมหนึ่งตำแหน่ง, e5 และ 5 จัดข้อความให้อยู่ในช่องกว้าง 5 ตัว, , เพิ่มตัวคั่นหลักพัน และ .0% แสดงเศษส่วนเป็นเปอร์เซ็นต์
เปลี่ยนค่าและรันโปรแกรมด้วย คอมไพเลอร์ Python ออนไลน์ของ CodeUtility โดยไม่ต้องติดตั้ง Python
แบบฝึกหัด
ลองเปลี่ยน input และทดสอบกรณีขอบก่อนใช้ชุดข้อมูลที่ใหญ่ขึ้น
- คาดเดา output ก่อนรัน
- รองรับ input ว่างหรือไม่ถูกต้อง
- แยก logic เป็นฟังก์ชันและเพิ่ม test case
ฝึกด้วยโจทย์
ใช้สิ่งที่เรียนในบทนี้แก้ปัญหาจริง ทุกโจทย์รันในเบราว์เซอร์ พร้อมการทดสอบทันทีและรีวิวจาก AI
- Multiplication Table Row List the first multiples of a number. ง่าย
- Count Uppercase Letters Count the capital letters in a text. ง่าย
- Initials From a Name Build uppercase initials from a full name. ง่าย