Metoda Template

Regular Expressions in Python

Maria Eugenia Inzaugarat

Data Scientist

Šablonové řetězce

  • Jednodušší syntaxe
  • Pomalejší než f-řetězce
  • Omezené: nepodporují specifikátory formátu
  • Vhodné pro práci s externě formátovanými řetězci
Regular Expressions in Python

Základní syntaxe

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

Substituce

  • Použití více $identifier
  • Použití proměnných
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

Substituce

  • Použijte ${identifier}, pokud za identifikátorem následují platné znaky

 

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

Substituce

  • Použijte $$ pro escapování znaku dolaru

 

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

Substituce

  • Vyvolá chybu, pokud chybí zástupný symbol
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

Substituce

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

Bezpečná substituce

  • Vždy se pokusí vrátit použitelný řetězec
  • Chybějící zástupné symboly zůstanou ve výsledném řetězci
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

Kterou metodu použít?

  • str.format():

    • Vhodný začátek. Koncepty platí i pro f-řetězce.
    • Kompatibilní se všemi verzemi Pythonu.
  • f-řetězce:

    • Doporučeno nadřadit všem ostatním metodám.
    • Pouze pro moderní verze Pythonu (3.6+).
  • Šablonové řetězce:

    • Pro práci s externími nebo uživatelsky zadanými řetězci.
Regular Expressions in Python

Pojďme si procvičit!

Regular Expressions in Python

Preparing Video For Download...