Méthode Template

Expressions régulières en Python

Maria Eugenia Inzaugarat

Data Scientist

Chaînes Template

  • Syntaxe plus simple
  • Plus lent que les f-strings
  • Limité : n'accepte pas les spécificateurs de format
  • Utile avec des chaînes formatées à l'externe
Expressions régulières en Python

Syntaxe de 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'
Expressions régulières en Python

Substitution

  • Utiliser plusieurs $identifier
  • Utiliser des variables
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'
Expressions régulières en Python

Substitution

  • Utiliser ${identifier} lorsque des caractères valides suivent l'identifiant

 

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'
Expressions régulières en Python

Substitution

  • Utiliser $$ pour échapper le symbole du dollar

 

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!'
Expressions régulières en Python

Substitution

  • Provoque une erreur si un espace réservé manque
favorite = dict(flavor="chocolate")

my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
Expressions régulières en Python

Substitution

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
Expressions régulières en Python

Substitution sécurisée

  • Tente toujours de retourner une chaîne utilisable
  • Les espaces réservés manquants restent dans la chaîne résultante
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
Expressions régulières en Python

Que devriez-vous utiliser ?

  • str.format() :

    • Bon pour commencer. Les concepts s'appliquent aux f-strings.
    • Compatible avec toutes les versions de Python.
  • f-strings :

    • À privilégier par rapport aux autres méthodes.
    • Uniquement pour les versions modernes de Python (3.6+).
  • Chaînes Template :

    • À utiliser avec des chaînes externes ou fournies par l'utilisateur
Expressions régulières en Python

Passons à la pratique !

Expressions régulières en Python

Preparing Video For Download...