템플릿 기능은 코드를 건드리지 않고도 문자열 출력 형식을 바꿀수 있다.
$name는 뒤에 바로 공백이나 구분자가 있으면 충분하다.- 예: $cause. 처럼 문장 부호로 끝날 때.
${name}는 숫자나 문자 등 식별자에 포함될 수 있는 문자가 바로 이어질 때 경계를 명확하게 합니다.- 예: ${village}folk처럼 바로 문자열이 붙는 경우.
from string import Template
t = Template('${village}folk send $$10 to $cause.')
print(t.substitute(village='Nottingham', cause='the ditch fund'))
# Nottinghamfolk send $10 to the ditch fund.substitute vs safe_substitute
- substitute()는 값이 빠지면 KeyError가 발생
- 사용자 입력이 불완전할 수 있는 경우엔 safe_substitute()를 쓰면 채워지지 않는걸 그대로 둔다.
t = Template('Return the $item to $owner.')
d = dict(item='unladen swallow')
# t.substitute(d) # KeyError: 'owner'
print(t.safe_substitute(d))
# Return the unladen swallow to $owner.커스텀 구분자
- Template을 상속해 delimiter를 바꾸면 다른 기호를 플레이스홀더로 쓸 수 있다.
import time, os.path
from string import Template
class BatchRename(Template):
delimiter = '%'
fmt = 'Ashley_%n%f'
t = BatchRename(fmt)
date = time.strftime('%d%b%y')
photofiles = ['img_1074.jpg', 'img_1076.jpg',
'img_1077.jpg']
for i, filename in enumerate(photofiles):
base, ext = os.path.splitext(filename)
newname = t.substitute(d=date, n=i, f=ext)
print(f'{filename} --> {newname}')
# img_1074.jpg --> Ashley_0.jpg ...