Método Template

Expressões regulares em Python

Maria Eugenia Inzaugarat

Data Scientist

Template strings

  • Sintaxe mais simples
  • Mais lento que f-strings
  • Limitado: não aceita especificadores de formato
  • Bom com strings formatadas externamente
Expressões regulares em Python

Sintaxe 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'
Expressões regulares em Python

Substituição

  • Use vários $identifier
  • Use variáveis
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'
Expressões regulares em Python

Substituição

  • Use ${identifier} quando caracteres válidos seguem o 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'
Expressões regulares em Python

Substituição

  • Use $$ para escapar o cifrão

 

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!'
Expressões regulares em Python

Substituição

  • Gera erro quando falta 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'
Expressões regulares em Python

Substituição

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
Expressões regulares em Python

Substituição segura

  • Sempre tenta retornar uma string utilizável
  • Placeholders ausentes aparecem no 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'
Expressões regulares em Python

Qual usar?

  • str.format():

    • Bom para começar. Conceitos valem para f-strings.
    • Compatível com todas as versões do Python.
  • f-strings:

    • Normalmente a melhor opção.
    • Só em versões modernas do Python (3.6+).
  • Template strings:

    • Ao lidar com strings externas ou de usuários
Expressões regulares em Python

Vamos praticar!

Expressões regulares em Python

Preparing Video For Download...