Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Chuỗi định dạng f-strings trong Python

Python cung cấp cách mới để định dạng chuỗi, gọi là f-strings. Tính năng này có sẵn từ Python 3.6 theo PEP-498. Chúng được gọi là f-strings vì có tiền tố chữ 'f' trước chuỗi. Chữ 'f' cũng chỉ ra rằng chuỗi này dùng để định dạng.

Dưới đây là các ví dụ minh họa sử dụng f-strings.

Chương trình 1

name = 'Rajesh'
age = 13 * 3
fString = f'My name is {name} and my age is {age}'
print(fString)
# Có thể dùng chữ 'F' in hoa thay vì 'f' thường.
print(F'My name is {name} and my age is {age}')
# Vì fString đã được đánh giá, gán giá trị mới cho biến không thay đổi giá trị fstring.
name = 'Zack'
age = 44
print(fString)

Kết quả

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

Ví dụ 2 – f-strings với biểu thức và chuyển đổi

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}')
print(f'Default formatted Date = {dt}')
print(f'Modified Date format = {dt: %d/%m/%Y}')

Kết quả

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

Ví dụ 3: Đối tượng và thuộc tính

class Vehicle:
    Model = 0
    Brand = ''
    def __init__(self, Model, Brand):
        self.Model = Model
        self.Brand = Brand
    def __str__(self):
        return f'[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}')

Kết quả

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

Ví dụ 4: Gọi hàm

Chúng ta có thể gọi hàm trong định dạng f-strings.

def Multiply(x, y):
    return x * y
print(f'Multiply(40,20) = {Multiply(40,20)}')

Kết quả

Multiply(40,20) = 800

Ví dụ 5: Biểu thức Lambda

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)}')

Kết quả

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