วิธี Template

Regular Expressions ใน Python

Maria Eugenia Inzaugarat

Data Scientist

Template strings

  • ไวยากรณ์เรียบง่าย
  • ช้ากว่า f-strings
  • จำกัด: ไม่รองรับ format specifiers
  • เหมาะสำหรับสตริงที่จัดรูปแบบจากภายนอก
Regular Expressions ใน Python

ไวยากรณ์พื้นฐาน

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 ใน Python

การแทนที่

  • ใช้ $identifier หลายตัวได้
  • ใช้ตัวแปรได้
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 ใน Python

การแทนที่

  • ใช้ ${identifier} เมื่อมีอักขระที่ถูกต้องตามหลัง identifier

 

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 ใน Python

การแทนที่

  • ใช้ $$ เพื่อ escape เครื่องหมายดอลลาร์

 

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 ใน Python

การแทนที่

  • เกิดข้อผิดพลาดเมื่อ 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 ใน Python

การแทนที่

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 ใน Python

Safe substitution

  • พยายามคืนค่าสตริงที่ใช้ได้เสมอ
  • placeholder ที่หายไปจะปรากฏในสตริงผลลัพธ์
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 ใน Python

ควรใช้วิธีไหน?

  • str.format():

    • เหมาะสำหรับผู้เริ่มต้น แนวคิดนำไปใช้กับ f-strings ได้
    • รองรับ Python ทุกเวอร์ชัน
  • f-strings:

    • แนะนำให้ใช้มากกว่าวิธีอื่นเสมอ
    • ใช้ได้เฉพาะ Python เวอร์ชันใหม่ (3.6+)
  • Template strings:

    • เหมาะเมื่อใช้กับสตริงจากภายนอกหรือที่ผู้ใช้กำหนด
Regular Expressions ใน Python

มาฝึกกันเถอะ!

Regular Expressions ใน Python

Preparing Video For Download...