수색…


템플릿을 이용한 간단한 데이터 출력 프로그램

from string import Template

data = dict(item = "candy", price = 8, qty = 2)

# define the template
t = Template("Simon bought $qty $item for $price dollar")   
print(t.substitute(data))

산출:

Simon bought 2 candy for 8 dollar

템플릿은 $ 기반 대체 대신 $ 기반 대체를 지원합니다. Substitute (mapping, keywords)는 템플리트 대체를 수행하여 새 문자열을 반환합니다.

매핑은 템플릿 자리 표시 자와 일치하는 키가있는 사전 형 객체입니다. 이 예에서 price와 qty는 자리 표시 자입니다. 키워드 인수는 자리 표시 자로 사용할 수도 있습니다. 키워드가 둘 다 있으면 키워드의 자리 표시자가 우선합니다.

구분 기호 변경 중

"$"구분 기호는 다른 것으로 변경할 수 있습니다. 다음 예는 다음과 같습니다.

from string import Template

class MyOtherTemplate(Template):
    delimiter = "#"


data = dict(id = 1, name = "Ricardo")
t = MyOtherTemplate("My name is #name and I have the id: #id")
print(t.substitute(data))

여기에서 문서를 읽을 수 있습니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow