Phương thức Template

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Chuỗi Template

  • Cú pháp đơn giản hơn
  • Chậm hơn f-strings
  • Hạn chế: không hỗ trợ format specifiers
  • Tốt khi làm với chuỗi định dạng sẵn từ bên ngoài
Regular Expressions in Python

Cú pháp cơ bản

from string import Template

my_string = Template('Data science has been called $identifier')
my_string.substitute(identifier="sexiest job of the 21st century")
'Data science has been called sexiest job of the 21st century'
Regular Expressions in Python

Thay thế

  • Dùng nhiều $identifier
  • Dùng biến
from string import Template
job = "Data science"
name = "sexiest job of the 21st century"

my_string = Template('$title has been called $description')
my_string.substitute(title=job, description=name)
'Data science has been called sexiest job of the 21st century'
Regular Expressions in Python

Thay thế

  • Dùng ${identifier} khi sau identifier là ký tự hợp lệ

 

my_string = Template('I find Python very ${noun}ing but my sister has lost $noun')

my_string.substitute(noun="interest")
'I find Python very interesting but my sister has lost interest'
Regular Expressions in Python

Thay thế

  • Dùng $$ để escape dấu đô-la

 

my_string = Template('I paid for the Python course only $$ $price, amazing!')

my_string.substitute(price="12.50")
'I paid for the Python course only $ 12.50, amazing!'
Regular Expressions in Python

Thay thế

  • Báo lỗi khi thiếu placeholder
favorite = dict(flavor="chocolate")

my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
Regular Expressions in Python

Thay thế

favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')
try:
    my_string.substitute(favorite) 
except KeyError:
      print("missing information")
missing information
Regular Expressions in Python

Thay thế an toàn

  • Luôn cố trả về chuỗi dùng được
  • Placeholder thiếu sẽ hiển thị trong chuỗi kết quả
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
Regular Expressions in Python

Nên dùng cách nào?

  • str.format():

    • Dễ bắt đầu. Khái niệm áp dụng cho f-strings.
    • Hỗ trợ mọi phiên bản Python.
  • f-strings:

    • Nên ưu tiên hơn các phương pháp khác.
    • Chỉ dùng với Python hiện đại (3.6+).
  • Template strings:

    • Khi làm với chuỗi bên ngoài hoặc do người dùng cung cấp
Regular Expressions in Python

Ayo berlatih!

Regular Expressions in Python

Preparing Video For Download...