-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3_Template_String.py
38 lines (31 loc) · 1.53 KB
/
3_Template_String.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Simpler syntax;
# Slower than f-strings;
# Don't allow format specifiers (e for scientific notation; f for float; d for digit);
# Good when working with externally formatted strings
from string import Template
str1 = Template('$amino_acid helps prevent side effects due to drug reactions and toxic chemicals.')
str1.substitute(amino_acid='Cysteine')
# 'Cysteine helps prevent side effects due to drug reactions and toxic chemicals.'
Cys = 'Cysteine'
str1.substitute(amino_acid=Cys)
# 'Cysteine helps prevent side effects due to drug reactions and toxic chemicals.'
str2 = Template('Cysteine helps prevent side effects due to ${function}s and toxic chemicals.')
str2.substitute(function='drug reaction')
# 'Cysteine helps prevent side effects due to drug reactions and toxic chemicals.'
# $$ -> escape the dollar sign
str3 = Template('I paid for the Roma tomatoes only $$$price, amazing!') # $price -> identifier
str3.substitute(price='1.5')
# 'I paid for the Roma tomatoes only $1.5, amazing!'
favor_donut = dict(flavor='Glazed donut')
str4 = Template('I enjoy $flavor $donut very much!')
try:
str4.substitute(favor_donut)
except KeyError:
print('Missing information')
# Missing information
# Set up safe substitution
# .safe_substitute() avoids raising a KeyError because it uses the original placeholder if it is missing and consequently, always returns a usable string
favor_donut = dict(flavor='Glazed donut')
str4 = Template('I enjoy $flavor $donut very much!')
str4.safe_substitute(favor_donut)
# 'I enjoy Glazed donut $donut very much!'