Metoda Template

Expresii regulate în Python

Maria Eugenia Inzaugarat

Data Scientist

Template strings

  • Sintaxă mai simplă
  • Mai lent decât f-strings
  • Limitat: nu permite specificatori de format
  • Util pentru șiruri formatate extern
Expresii regulate în Python

Sintaxă de bază

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'
Expresii regulate în Python

Substituție

  • Utilizarea mai multor $identifier
  • Utilizarea variabilelor
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'
Expresii regulate în Python

Substituție

  • Folosiți ${identifier} când urmează caractere valide după identificator

 

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'
Expresii regulate în Python

Substituție

  • Folosiți $$ pentru a escapa semnul 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!'
Expresii regulate în Python

Substituție

  • Generează eroare când un substituent lipsește
favorite = dict(flavor="chocolate")

my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
Expresii regulate în Python

Substituție

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
Expresii regulate în Python

Substituție sigură

  • Încearcă întotdeauna să returneze un șir utilizabil
  • Substituenții lipsă apar în șirul rezultat
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
Expresii regulate în Python

Ce metodă să folosesc?

  • str.format():

    • Bun punct de plecare. Conceptele se aplică și la f-strings.
    • Compatibil cu toate versiunile de Python.
  • f-strings:

    • Recomandat peste toate metodele.
    • Potrivit doar pentru versiuni moderne de Python (3.6+).
  • Template strings:

    • Când se lucrează cu șiruri externe sau furnizate de utilizator.
Expresii regulate în Python

Să exersăm!

Expresii regulate în Python

Preparing Video For Download...