Template-methode

Regular expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Templatestrings

  • Eenvoudige syntax
  • Trager dan f-strings
  • Beperkt: geen format-specifiers
  • Handig voor extern geformatteerde strings
Regular expressions in Python

Basissyntax

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'
Regular expressions in Python

Substitutie

  • Gebruik meerdere $identifier
  • Gebruik variabelen
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'
Regular expressions in Python

Substitutie

  • Gebruik ${identifier} als er geldige tekens op de identifier volgen

 

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'
Regular expressions in Python

Substitutie

  • Gebruik $$ om het dollarteken te escapen

 

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!'
Regular expressions in Python

Substitutie

  • Geef een error als placeholder ontbreekt
favorite = dict(flavor="chocolate")

my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
Regular expressions in Python

Substitutie

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
Regular expressions in Python

Veilige substitutie

  • Probeert altijd een bruikbare string te geven
  • Ontbrekende placeholders blijven in de output staan
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

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

Welke kies je?

  • str.format():

    • Goed om mee te beginnen. Concepten gelden ook voor f-strings.
    • Compatibel met alle Python-versies.
  • f-strings:

    • Meestal de beste keuze.
    • Alleen voor moderne Python-versies (3.6+).
  • Templatestrings:

    • Bij externe of door gebruikers aangeleverde strings
Regular expressions in Python

Laten we oefenen!

Regular expressions in Python

Preparing Video For Download...