Advertisement
DeaD_EyE

template strings Python 3.14.0b1

May 10th, 2025
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.70 KB | None | 0 0
  1. from datetime import datetime as DateTime
  2. from string.templatelib import Template, Interpolation
  3. from html import escape as html_escape
  4.  
  5.  
  6. def html(template: Template) -> str:
  7.     if not isinstance(template, Template):
  8.         raise TypeError("Normal Strings are not allowed. Use a template string")
  9.  
  10.     parts = []
  11.  
  12.     for item in template:
  13.         match item:
  14.             case Interpolation():
  15.                 parts.append(html_escape(str(item.value)))
  16.             case str():
  17.                 parts.append(item)
  18.  
  19.     return "".join(parts)
  20.  
  21. world = "<b>world</b>"
  22. dt = DateTime.now()
  23. print(html(t"Hello {world}. {dt}"))
  24.  
  25. try:
  26.     html(f"Wrong {world}")
  27. except TypeError as e:
  28.     print(e)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement