Template method

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Template strings

  • Simpler syntax
  • Slower than f-strings
  • Limited: don't allow format specifiers
  • Good when working with externally formatted strings
Regular Expressions in Python

Basic syntax

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

Substitution

  • Use many $identifier
  • Use 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'
Regular Expressions in Python

Substitution

  • Use ${identifier} when valid characters follow identifier

 

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

Substitution

  • Use $$ to escape the dollar sign

 

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

Substitution

  • Raise error when placeholder is missing
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

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

Safe substitution

  • Always tries to return a usable string
  • Missing placeholders will appear in resulting string
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

Which should I use?

  • str.format():

    • Good to start with. Concepts apply to f-strings.
    • Compatible with all versions of Python.
  • f-strings:

    • Always advisable above all methods.
    • Only suitable when working with modern versions of Python (3.6+).
  • Template strings:

    • When working with external or user-provided strings
Regular Expressions in Python

Let's practice!

Regular Expressions in Python

Preparing Video For Download...