ตอนนี้ Python มีวิธีใหม่ในการจัดรูปแบบสตริงที่เรียกว่า f-strings คุณลักษณะนี้มีให้ใน Python 3.6 ภายใต้ PEP-498 พวกเขาถูกเรียกว่า (f-string) เนื่องจากตัวอักษร 'f' นำหน้าด้วยสตริง ตัวอักษร 'f' ยังระบุว่าสตริง f เหล่านี้ใช้สำหรับการจัดรูปแบบได้
ด้านล่างนี้คือตัวอย่างบางส่วนเพื่อสาธิตการใช้ f-strings
โปรแกรม#1
name = 'Rajesh'
age = 13 * 3
fString = f'My name is {name} and my age is {age}'
print(fString)
#We can use Uppercase 'F' instead of lowercase 'f'.
print(F'My name is {name} and my age is {age}')
#As the fString valuation is done, giving another value to the variable will not change fstring value.
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
ตัวอย่าง#2 – f-strings พร้อมนิพจน์และการแปลง
จากวันที่และเวลานำเข้าวันที่เวลา
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}')
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
ตัวอย่าง#3:ออบเจ็กต์และแอตทริบิวต์
class Vehicle:
Model = 0
Brand = ''
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
ตัวอย่าง#4:การเรียกใช้ฟังก์ชัน
เราสามารถเรียกใช้ฟังก์ชันในรูปแบบ f-strings ได้เช่นกัน
def Multiply(x,y):
return x*y
print( f'Multiply(40,20) = {Multiply(40,20)}') ผลลัพธ์
Multiply(40,20) = 800
ตัวอย่าง # 5:นิพจน์แลมบ์ดา
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 24 is: 16