f-string หรือ formatted string literals เป็นฟีเจอร์ใหม่ที่ถูกเพิ่มเข้ามาใน Python 3.6 เพื่อให้การจัดรูปแบบข้อความ (string formatting) ทำได้ง่ายและชัดเจนยิ่งขึ้น เมื่อเทียบกับวิธีการจัดรูปแบบข้อความในเวอร์ชันก่อนๆ เช่น การใช้ % หรือ .format(). ฟีเจอร์นี้ช่วยให้สามารถใส่ expressions ของ Python ได้โดยตรงภายใน string literals โดยใช้ {} เป็นตัวครอบ และนำหน้าด้วยตัวอักษร f หรือ F ก่อน string literal
ตัวอย่างที่ 1: การใช้งานพื้นฐาน
name = "John" age = 30 print(f"Hello, {name}. You are {age} years old.")
ผลลัพธ์:
Hello, John. You are 30 years old.
ตัวอย่างที่ 2: การใช้งานกับการคำนวณ
x = 10 y = 5 print(f"{x} times {y} is {x * y}")
ผลลัพธ์:
10 times 5 is 50
ตัวอย่างที่ 3: การใช้งานกับการเรียกใช้ฟังก์ชัน
def get_title(): return "Doctor" name = "Jane" print(f"The {get_title()} {name} is in.")
ผลลัพธ์:
The Doctor Jane is in.
ตัวอย่างที่ 4: การใช้งานกับการจัดรูปแบบตัวเลข
number = 123.4567 print(f"The number is {number:.2f}")
ผลลัพธ์:
The number is 123.46