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

Formatted String Literals (f-strings) ใน Python

Python 3.6+ มีวิธีจัดรูปแบบสตริงใหม่เรียกว่า f-strings (PEP 498) ใช้ตัวอักษร 'f' นำหน้าสตริง ทำให้ใส่ตัวแปรและนิพจน์ได้โดยตรงในสตริง อ่านง่ายและเร็วกว่ารูปแบบเก่า

ตัวอย่างพื้นฐาน

name = 'Rajesh'
age = 13 * 3
fString = f'My name is {name} and my age is {age}'
print(fString)
# ใช้ F พิมพ์ใหญ่ก็ได้
print(F'My name is {name} and my age is {age}')

# fString คำนวณค่าแล้วเก็บไว้ การเปลี่ยนตัวแปรภายหลังไม่ส่งผล
name = 'Zack'
age = 44
print(fString)  # ยังคงเป็นค่าเดิม

ผลลัพธ์

My name is Rajesh and my age is 39
My name is Rajesh and my age is 39
My name is Rajesh and my age is 39

f-strings กับนิพจน์และการแปลง

from datetime import datetime

name = 'Rajesh'
age = 13 * 3
dt = datetime.now()

print(f' Age after ten years will be {age + 10}')
print(f'Name with quotes = {name!r}')  # !r ใช้ repr()
print(f'Default formatted Date = {dt}')
print(f'Modified Date format = {dt: %d/%m/%Y}')

ผลลัพธ์

Age after ten years will be 49
Name with quotes = 'Rajesh'
Default formatted Date = 2019-02-11 14:52:05.307841
Modified Date format = 11/02/2019

f-strings กับออบเจ็กต์และแอตทริบิวต์

class Vehicle:
    def __init__(self, Model, Brand):
        self.Model = Model
        self.Brand = Brand
    def __str__(self):
        return f'E[Model={self.Model}, Brand = {self.Brand}]'

Car = Vehicle(2018, 'Maruti')
print(Car)
print(f'Vehicle: {Car}\nModel is {Car.Model} and Brand is {Car.Brand}')

ผลลัพธ์

E[Model=2018, Brand = Maruti]
Vehicle: E[Model=2018, Brand = Maruti]
Model is 2018 and Brand is Maruti

เรียกใช้ฟังก์ชันใน f-strings

def Multiply(x, y):
    return x * y

print(f'Multiply(40,20) = {Multiply(40,20)}')

ผลลัพธ์

Multiply(40,20) = 800

Lambda expressions ใน f-strings

x = -40.9
print(f' Lambda absolute of (-40.9) is : {(lambda x: abs(x)) (x)}')
print(f' Lambda Square of 2^4 is: {(lambda x: pow(x, 2)) (4)}')

ผลลัพธ์

Lambda absolute of (-40.9) is : 40.9
Lambda Square of 2^4 is: 16

ข้อดีของ f-strings

  • อ่านง่าย เข้าใจง่าย
  • รองรับนิพจน์ซับซ้อนได้
  • เร็วกว่า % formatting และ .format()
  • รองรับ format specifier เหมือนเดิม (เช่น :.2f, :05d)