Método Template

Expresiones regulares en Python

Maria Eugenia Inzaugarat

Data Scientist

Cadenas Template

  • Sintaxis más simple
  • Más lentas que las f-strings
  • Limitadas: no permiten especificadores de formato
  • Útiles con cadenas formateadas externamente
Expresiones regulares en Python

Sintaxis básica

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'
Expresiones regulares en Python

Sustitución

  • Usa muchos $identifier
  • Usa 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'
Expresiones regulares en Python

Sustitución

  • Usa ${identifier} cuando haya caracteres válidos tras el identificador

 

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'
Expresiones regulares en Python

Sustitución

  • Usa $$ para escapar el signo de dólar

 

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!'
Expresiones regulares en Python

Sustitución

  • Lanza error si falta 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'
Expresiones regulares en Python

Sustitución

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
Expresiones regulares en Python

Sustitución segura

  • Siempre intenta devolver una cadena usable
  • Los placeholders que falten aparecen en el resultado
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
Expresiones regulares en Python

¿Cuál usar?

  • str.format():

    • Buena para empezar. Conceptos aplican a f-strings.
    • Compatible con todas las versiones de Python.
  • f-strings:

    • Recomendadas sobre los demás métodos.
    • Solo en versiones modernas de Python (3.6+).
  • Cadenas Template:

    • Al trabajar con cadenas externas o de usuarios
Expresiones regulares en Python

¡Vamos a practicar!

Expresiones regulares en Python

Preparing Video For Download...