Metode template

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Template string

  • Sintaks lebih sederhana
  • Lebih lambat daripada f-string
  • Terbatas: tidak mendukung format specifier
  • Cocok saat bekerja dengan string berformat eksternal
Regular Expressions in Python

Sintaks dasar

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

Substitusi

  • Gunakan banyak $identifier
  • Gunakan variabel
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

Substitusi

  • Pakai ${identifier} saat ada karakter valid setelah 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 in Python

Substitusi

  • Gunakan $$ untuk escape tanda dolar

 

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

Substitusi

  • Munculkan error saat placeholder hilang
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

Substitusi

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

Safe substitution

  • Selalu berupaya mengembalikan string yang dapat dipakai
  • Placeholder yang hilang akan muncul di hasil string
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

Apa yang sebaiknya digunakan?

  • str.format():

    • Bagus untuk mulai. Konsepnya berlaku pada f-string.
    • Kompatibel dengan semua versi Python.
  • f-strings:

    • Umumnya paling disarankan.
    • Hanya untuk Python modern (3.6+).
  • Template strings:

    • Saat memakai string eksternal atau dari pengguna
Regular Expressions in Python

Ayo berlatih!

Regular Expressions in Python

Preparing Video For Download...