Metodo Template

Espressioni regolari in Python

Maria Eugenia Inzaugarat

Data Scientist

Stringhe Template

  • Sintassi più semplice
  • Più lento delle f-string
  • Limitato: niente specificatori di formato
  • Utile con stringhe formattate esternamente
Espressioni regolari in Python

Sintassi di base

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'
Espressioni regolari in Python

Sostituzione

  • Usa molti $identifier
  • Usa variabili
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'
Espressioni regolari in Python

Sostituzione

  • Usa ${identifier} quando seguono caratteri validi dopo l'identificatore

 

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'
Espressioni regolari in Python

Sostituzione

  • Usa $$ per fare l'escape del simbolo del dollaro

 

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!'
Espressioni regolari in Python

Sostituzione

  • Genera errore se manca un 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'
Espressioni regolari in Python

Sostituzione

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
Espressioni regolari in Python

Sostituzione sicura

  • Cerca sempre di restituire una stringa utilizzabile
  • I placeholder mancanti restano nella stringa risultante
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

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

Quale usare?

  • str.format():

    • Ottimo per iniziare. I concetti valgono anche per le f-string.
    • Compatibile con tutte le versioni di Python.
  • f-string:

    • In genere la scelta migliore.
    • Solo per versioni moderne di Python (3.6+).
  • Template strings:

    • Quando lavori con stringhe esterne o fornite dall'utente
Espressioni regolari in Python

Let's practice!

Espressioni regolari in Python

Preparing Video For Download...