2.3. Syntax T-String
New string literal prefix:
t'...'Stands for Template String
Similar to f-strings (formatted string literals)
Uses
string.templatelibmoduleSince Python 3.14
2.3.1. Problem
The following code constructs a SQL query using f-strings
However, it does not provide a way to analyze the structure of the query
It poses security risks (SQL injection) if user inputs are not sanitized
>>> username = 'alice'
>>> password = 'secret'
>>> query = f'SELECT * FROM users WHERE username="{username}" AND password="{password}"'
>>>
>>> print(query)
SELECT * FROM users WHERE username="alice" AND password="secret"
2.3.2. Solution
Use t-strings to create a template representation of the SQL query
This allows for safer handling and analysis of the query structure
>>> username = 'alice'
>>> password = 'secret'
>>> query = t'SELECT * FROM users WHERE username="{username}" AND password="{password}"'
>>>
>>> print(query)
Template(strings=('SELECT * FROM users WHERE username="', '" AND password="', '"'),
interpolations=(Interpolation('alice', 'username', None, ''),
Interpolation('secret', 'password', None, '')))
2.3.3. Example
>>> name = 'Alice'
>>> day = 'Friday'
>>>
>>> template = t'Hello {name}! Today is {day}.'
>>>
>>> template
Template(strings=('Hello ', '! Today is ', '.'),
interpolations=(Interpolation('Alice', 'name', None, ''),
Interpolation('Friday', 'day', None, '')))
2.3.4. Parsing
https://docs.python.org/id/3/library/string.templatelib.html#string.templatelib.Interpolation
value- the value of the expressionexpression- text found inside the curly brackets ({and}), including any whitespace, excluding the curly brackets themselves, and ending before the first!,:, or=if any is presentconversion-a,r,sorNone, depending on whether a conversion flag was present, ie."Hello {user!r}"format_spec- the format specifier, ie."Hello {value:.2f}"or"Hello {value:myfspec}"
>>> from string.templatelib import Interpolation, Template
>>>
>>>
>>> def parse(template):
... if not isinstance(template, Template):
... raise TypeError('t-string expected')
... result = []
... for item in template:
... if isinstance(item, str):
... # ... <your code here> ...
... iterpolated = item
... result.append(iterpolated)
... elif isinstance(item, Interpolation):
... value = item.value
... expression = item.expression
... conversion = item.conversion
... format_spec = item.format_spec
... iterpolated = format(value, format_spec)
... result.append(iterpolated)
... return ''.join(result)
>>>
>>>
>>> name = 'Alice'
>>> day = 'Friday'
>>>
>>> template = t'Hello {name}! Today is {day}.'
>>>
>>> parse(template)
'Hello Alice! Today is Friday.'