Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

String Template Class ใน Python: $placeholder แทน %s

string.Template เป็นวิธีจัดรูปแบบสตริงที่ใช้ $ แทน % ใช้งานง่ายและปลอดภัยกว่า (ไม่ eval code) เหมาะกับ user-generated templates

3 เมธอดหลัก

Methodคำอธิบาย
Template(template)Constructor รับ template string
substitute(mapping, **kw)แทนค่า, โยน KeyError ถ้า placeholder ขาด
safe_substitute(mapping, **kw)เหมือน substitute แต่ไม่โยน error ถ้า placeholder ขาด (คงค่าเดิม)

ตัวอย่างพื้นฐาน

from string import Template

t = Template('$when, $who $action $what.')

# 1. keyword arguments
s = t.substitute(when='In the winter', who='Rajesh', action='drinks', what='Coffee')
print(s)  # In the winter, Rajesh drinks Coffee.

# 2. dictionary
d = {"when": "In the winter", "who": "Rajesh", "action": "drinks", "what": "Coffee"}
s = t.substitute(**d)
print(s)  # In the winter, Rajesh drinks Coffee.

# 3. safe_substitute (ไม่ error ถ้าขาด)
s = t.safe_substitute(when='In the winter', who='Rajesh')  # ขาด action, what
print(s)  # In the winter, Rajesh $action $what.

Attribute: template

>> t.template
'$when, $who $action $what.'

Escape $ sign

t = Template('$$ is called $name')
print(t.substitute(name='Dollar'))  # $ is called Dollar

ใช้ ${identifier} เมื่อตัวอักษรต่อเนื่อง

t = Template('$noun adjective is ${noun}ing')
print(t.substitute(noun='Test'))  # Test adjective is Testing

เมื่อไหร่ควรใช้ Template?

  • Template มาจากผู้ใช้/ config file (ปลอดภัย ไม่มี code execution)
  • รูปแบบง่าย ไม่ต้องการ formatting ซับซ้อน
  • Internationalization (i18n) - แยก template ออกจาก logic