string.templatelib
— Suporte para literais de string template¶
Código-fonte: Lib/string/templatelib.py
Strings template¶
Adicionado na versão 3.14.
Strings template são um mecanismo para processamento personalizado de strings. Elas têm toda a flexibilidade das Literais de strings formatadas do Python, mas retornam uma instância Template
que dá acesso às partes estáticas e interpoladas (entre chaves) de uma string antes de serem combinadas.
Para escrever uma t-string, use um prefixo 't'
em vez de 'f'
, assim:
>>> pi = 3.14
>>> t't-strings são novas no Python {pi!s}!'
Template(
strings=('t-strings são novas no Python ', '!'),
interpolations=(Interpolation(3.14, 'pi', 's', ''),)
)
Tipos¶
- class string.templatelib.Template¶
A classe
Template
descreve o conteúdo de uma string template. Ela é imutável, o que significa que os atributos de um template não podem ser reatribuídos.A maneira mais comum de criar uma instância de
Template
é usar a sintaxe de literal de string template. Essa sintaxe é idêntica à de f-strings, exceto pelo fato de usar um prefixot
no lugar de umf
:>>> cheese = 'Red Leicester' >>> template = t"We're fresh out of {cheese}, sir." >>> type(template) <class 'string.templatelib.Template'>
Os templates são armazenados como sequências de literais
strings
e dinâmicosinterpolations
. Um atributovalues
contém os valores das interpolações:>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.strings ('Ah! We do have ', '.') >>> template.interpolations (Interpolation('Camembert', ...),) >>> template.values ('Camembert',)
A tupla
strings
tem um elemento a mais queinterpolations
evalues
; as interpolações “pertencem” às strings. Isso pode ser mais fácil de entender quando as tuplas estão alinhadastemplate.strings: ('Ah! We do have ', '.') template.values: ( 'Camembert', )
Atributos
- strings: tuple[str, ...]¶
Uma
tuple
das strings estáticas no template.>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.strings ('Ah! We do have ', '.')
Strings vazias estão incluídas na tupla:
>>> response = 'We do have ' >>> cheese = 'Camembert' >>> template = t'Ah! {response}{cheese}.' >>> template.strings ('Ah! ', '', '.')
A tupla
strings
nunca está vazia e sempre contém uma string a mais que as tuplasinterpolations
evalues
:>>> t''.strings ('',) >>> t''.values () >>> t'{'cheese'}'.strings ('', '') >>> t'{'cheese'}'.values ('cheese',)
- interpolations: tuple[Interpolation, ...]¶
Uma
tuple
das interpolações no template.>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.interpolations (Interpolation('Camembert', 'cheese', None, ''),)
A tupla
interpolações
pode estar vazia e sempre contém um valor a menos que a tuplastrings
:>>> t'Red Leicester'.interpolations ()
- values: tuple[object, ...]¶
Uma tupla de todos os valores interpolados no template.
>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.values ('Camembert',)
A tupla
values
sempre tem o mesmo comprimento que a tuplainterpolations
. Isso sempre equivale atuple(i.value for i in template.interpolations)
.
Métodos
- __new__(*args: str | Interpolation)¶
Embora a sintaxe de literal seja a maneira mais comum de criar um
Template
, também é possível criá-las diretamente usando o construtor:>>> from string.templatelib import Interpolation, Template >>> cheese = 'Camembert' >>> template = Template( ... 'Ah! We do have ', Interpolation(cheese, 'cheese'), '.' ... ) >>> list(template) ['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']
Se várias strings forem passadas consecutivamente, elas serão concatenadas em um único valor no atributo
strings
. Por exemplo, o código a seguir cria umaTemplate
com uma única string final:>>> from string.templatelib import Template >>> template = Template('Ah! We do have ', 'Camembert', '.') >>> template.strings ('Ah! We do have Camembert.',)
Se várias interpolações forem passadas consecutivamente, elas serão tratadas como interpolações separadas e uma string vazia será inserida entre elas. Por exemplo, o código a seguir cria um modelo com espaços reservados vazios no atributo
strings
:>>> from string.templatelib import Interpolation, Template >>> template = Template( ... Interpolation('Camembert', 'cheese'), ... Interpolation('.', 'punctuation'), ... ) >>> template.strings ('', '', '')
- iter(template)
Itera sobre o template, produzindo cada string não-vazia e
Interpolation
em ordem correta.>>> cheese = 'Camembert' >>> list(t'Ah! We do have {cheese}.') ['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']
Cuidado
Empty strings are not included in the iteration:
>>> response = 'We do have ' >>> cheese = 'Camembert' >>> list(t'Ah! {response}{cheese}.') ['Ah! ', Interpolation('We do have ', 'response', None, ''), Interpolation('Camembert', 'cheese', None, ''), '.']
- template + other
- template += other
Concatena este template com outro, retornando uma nova instância
Template
:>>> cheese = 'Camembert' >>> list(t'Ah! ' + t'We do have {cheese}.') ['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']
Concatenating a
Template
and astr
is not supported. This is because it is unclear whether the string should be treated as a static string or an interpolation. If you want to concatenate aTemplate
with a string, you should either wrap the string directly in aTemplate
(to treat it as a static string) or use anInterpolation
(to treat it as dynamic):>>> from string.templatelib import Interpolation, Template >>> template = t'Ah! ' >>> # Treat 'We do have ' as a static string >>> template += Template('We do have ') >>> # Treat cheese as an interpolation >>> cheese = 'Camembert' >>> template += Template(Interpolation(cheese, 'cheese')) >>> list(template) ['Ah! We do have ', Interpolation('Camembert', 'cheese', None, '')]
- class string.templatelib.Interpolation¶
The
Interpolation
type represents an expression inside a template string. It is immutable, meaning that attributes of an interpolation cannot be reassigned.As interpolações oferecem suporte à correspondência de padrões, permitindo que você compare seus atributos com a instrução match:
>>> from string.templatelib import Interpolation >>> interpolation = t'{1. + 2.:.2f}'.interpolations[0] >>> interpolation Interpolation(3.0, '1. + 2.', None, '.2f') >>> match interpolation: ... case Interpolation(value, expression, conversion, format_spec): ... print(value, expression, conversion, format_spec, sep=' | ') ... 3.0 | 1. + 2. | None | .2f
Atributos
- expression: str¶
O texto de uma expressão Python válida ou uma string vazia.
The
expression
is the original text of the interpolation’s Python expression, if the interpolation was created from a t-string literal. Developers creating interpolations manually should either set this to an empty string or choose a suitable valid Python expression.>>> t'{1 + 2}'.interpolations[0].expression '1 + 2'
- conversion: Literal['a', 'r', 's'] | None¶
A conversão a ser aplicada ao valor, ou
None
.The
conversion
is the optional conversion to apply to the value:>>> t'{1 + 2!a}'.interpolations[0].conversion 'a'
Nota
Unlike f-strings, where conversions are applied automatically, the expected behavior with t-strings is that code that processes the
Template
will decide how to interpret and whether to apply theconversion
. For convenience, theconvert()
function can be used to mimic f-string conversion semantics.
- format_spec: str¶
A especificação de formato a ser aplicada ao valor.
The
format_spec
is an optional, arbitrary string used as the format specification to present the value:>>> t'{1 + 2:.2f}'.interpolations[0].format_spec '.2f'
Nota
Unlike f-strings, where format specifications are applied automatically via the
format()
protocol, the expected behavior with t-strings is that code that processes the interpolation will decide how to interpret and whether to apply the format specification. As a result,format_spec
values in interpolations can be arbitrary strings, including those that do not conform to theformat()
protocol.
Métodos
- __new__(value: object, expression: str, conversion: Literal['a', 'r', 's'] | None = None, format_spec: str = '')¶
Create a new
Interpolation
object from component parts.- Parâmetros:
value – O resultado avaliado e dentro do escopo da interpolação.
expression – O texto de uma expressão Python válida ou uma string vazia.
conversion – The conversion to be used, one of
None
,'a'
,'r'
, or's'
.format_spec – Uma string arbitrária opcional usada como especificação de formato para apresentar o valor.
Funções auxiliares¶
- string.templatelib.convert(obj, /, conversion)¶
Aplica a semântica de conversão de literal de string formatada ao objeto obj fornecido. Isso é frequentemente útil para lógica de processamento de string template personalizada.
Atualmente, há três sinalizadores de conversão suportados:
's'
which callsstr()
on the value (like!s
),'r'
which callsrepr()
(like!r
), and'a'
which callsascii()
(like!a
).
Se o sinalizador de conversão é
None
, obj é retornado sem alterações.