Regular Expressions in Python
Maria Eugenia Inzaugarat
Data Scientist
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'
$identifier
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'
${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'
$$
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!'
favorite = dict(flavor="chocolate")
my_string = Template('I love $flavor $cake very much')
my_string.substitute(favorite)
Traceback (most recent call last):
KeyError: 'cake'
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
favorite = dict(flavor="chocolate") my_string = Template('I love $flavor $cake very much')
my_string.safe_substitute(favorite)
'I love chocolate $cake very much'
str.format()
:
f-strings:
Template strings:
Regular Expressions in Python