पायथन का string.Template क्लास सरल टेम्प्लेट स्ट्रिंग्स बनाने के लिए उपयोग होता है। यह पायथन 2.4 में पेश किया गया था। % फॉर्मेटिंग के विपरीत, यह प्लेसहोल्डर के लिए $ साइन का उपयोग करता है।
Template क्लास के मेथड्स
Template(template): कंस्ट्रक्टर, टेम्प्लेट स्ट्रिंग लेता है।substitute(mapping, **kwargs): मान प्रतिस्थापित करता है। प्लेसहोल्डर गायब होने परKeyErrorउठाता है।safe_substitute(mapping, **kwargs):substituteजैसा लेकिन गायब प्लेसहोल्डर को वैसे ही छोड़ देता है (कोई त्रुटि नहीं)।
बुनियादी उदाहरण
from string import Template
t = Template('$when, $who $action $what.')
# कीवर्ड आर्गुमेंट्स
s = t.substitute(when='In the winter', who='Rajesh', action='drinks', what='Coffee')
print(s) # In the winter, Rajesh drinks Coffee.
# डिक्शनरी के साथ
d = {"when": "In the winter", "who": "Rajesh", "action": "drinks", "what": "Coffee"}
s = t.substitute(**d)
print(s) # In the winter, Rajesh drinks Coffee.
safe_substitute()
s = t.safe_substitute(when='In the winter', who='Rajesh', action='drinks')
# 'what' गायब है - कोई त्रुटि नहीं, प्लेसहोल्डर बना रहता है
print(s) # In the winter, Rajesh drinks $what.
टेम्प्लेट स्ट्रिंग एक्सेस करना
print('Template String:', t.template)
# Template String: $when, $who $action $what.
$ साइन एस्केप करना
t = Template('$$ is called $name')
s = t.substitute(name='Dollar')
print(s) # $ is called Dollar
प्लेसहोल्डर पहचानकर्ता: ${identifier}
जब वैध पहचानकर्ता वर्ण प्लेसहोल्डर के बाद आते हों लेकिन उसका हिस्सा न हों:
t = Template('$noun adjective is ${noun}ing')
s = t.substitute(noun='Test')
print(s) # Test adjective is Testing
यहां ${noun} आवश्यक है ताकि ing प्लेसहोल्डर का हिस्सा न बने।
उन्नत: कस्टम डिलीमीटर
आप Template को सबक्लास करके डिलीमीटर बदल सकते हैं:
class MyTemplate(Template):
delimiter = '%'
t = MyTemplate('%name is %age years old')
print(t.substitute(name='Alice', age=30)) # Alice is 30 years old
कब उपयोग करें?
- उपयोगकर्ता-प्रदत्त टेम्प्लेट्स के लिए (सुरक्षा: कोई कोड निष्पादन नहीं)।
- सरल प्लेसहोल्डर प्रतिस्थापन के लिए।
- जब % या
{}फॉर्मेटिंग बहुत जटिल या असुरक्षित हो।