Metoda szablonu

Wyrażenia regularne w Pythonie

Maria Eugenia Inzaugarat

Data Scientist

Szablony ciągów

  • Prostsza składnia
  • Wolniejsze niż f-strings
  • Ograniczone: brak specyfikatorów formatu
  • Przydatne przy ciągach formatowanych zewnętrznie
Wyrażenia regularne w Pythonie

Podstawowa składnia

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'
Wyrażenia regularne w Pythonie

Podstawianie

  • Użyj wielu $identifier
  • Użyj zmiennych
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'
Wyrażenia regularne w Pythonie

Podstawianie

  • Użyj ${identifier}, gdy po identyfikatorze następują prawidłowe znaki

 

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'
Wyrażenia regularne w Pythonie

Podstawianie

  • Użyj $$, aby użyć znaku dolara dosłownie

 

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!'
Wyrażenia regularne w Pythonie

Podstawianie

  • Błąd przy brakującym symbolu zastępczym
favorite = dict(flavor="chocolate")

my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
Wyrażenia regularne w Pythonie

Podstawianie

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
Wyrażenia regularne w Pythonie

Bezpieczne podstawianie

  • Zawsze stara się zwrócić użyteczny ciąg
  • Brakujące symbole zastępcze pozostają w wynikowym ciągu
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')

my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
Wyrażenia regularne w Pythonie

Którą metodę wybrać?

  • str.format():

    • Dobry punkt startowy. Koncepcje stosują się do f-strings.
    • Kompatybilny ze wszystkimi wersjami Pythona.
  • f-strings:

    • Zalecane ponad inne metody.
    • Tylko dla nowoczesnych wersji Pythona (3.6+).
  • Szablony:

    • Gdy pracujemy z ciągami zewnętrznymi lub podanymi przez użytkownika
Wyrażenia regularne w Pythonie

Czas na ćwiczenia!

Wyrażenia regularne w Pythonie

Preparing Video For Download...