string.templatelib --- テンプレート文字列リテラルのサポート¶
ソースコード: Lib/string/templatelib.py
テンプレート文字列¶
Added in version 3.14.
テンプレート文字列は、文字列処理をカスタマイズするための仕組みです。
Python の f-strings と同じ柔軟性を持ちますが、静的な部分と波括弧で囲んだ補間部分に、それらが結合される 前に アクセスできる Template インスタンスを返します。
t-stringを書くには、このようにプレフィックスとして 'f' の代わりに 't' を使用します:
>>> pi = 3.14
>>> t't-strings are new in Python {pi!s}!'
Template(
strings=('t-strings are new in Python ', '!'),
interpolations=(Interpolation(3.14, 'pi', 's', ''),)
)
型¶
- class string.templatelib.Template¶
Templateクラスはテンプレート文字列の内容を表します。 イミュータブルであり、テンプレートの属性には再代入できません。Templateインスタンスを作成する最も一般的な方法は、テンプレート文字列リテラルの構文 を使うことです。 この構文は、fの代わりにtを前に付ける点を除いて、f 文字列 と同じです。>>> cheese = 'Red Leicester' >>> template = t"We're fresh out of {cheese}, sir." >>> type(template) <class 'string.templatelib.Template'>
テンプレートは、リテラル部分の
stringsと動的な部分のinterpolationsのシーケンスとして格納されます。values属性は補間される値を保持します。>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.strings ('Ah! We do have ', '.') >>> template.interpolations (Interpolation('Camembert', ...),) >>> template.values ('Camembert',)
stringsタプルはinterpolationsとvaluesより要素が 1 つ多く、補間部分は文字列の間に入ります。 タプルの要素の位置をそろえて並べると分かりやすくなります。template.strings: ('Ah! We do have ', '.') template.values: ( 'Camembert', )
属性
- strings: tuple[str, ...]¶
テンプレート内の静的な文字列の
tuple。>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.strings ('Ah! We do have ', '.')
タプルには空文字列も 含まれます。
>>> response = 'We do have ' >>> cheese = 'Camembert' >>> template = t'Ah! {response}{cheese}.' >>> template.strings ('Ah! ', '', '.')
stringsタプルは空になることはなく、interpolationsタプルやvaluesタプルより常に文字列が 1 つ多く含まれます。>>> t''.strings ('',) >>> t''.values () >>> t'{'cheese'}'.strings ('', '') >>> t'{'cheese'}'.values ('cheese',)
- interpolations: tuple[Interpolation, ...]¶
テンプレート内の補間部分の
tuple。>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.interpolations (Interpolation('Camembert', 'cheese', None, ''),)
interpolationsタプルは空の場合もあり、常にstringsタプルより値が 1 つ少なくなります。>>> t'Red Leicester'.interpolations ()
- values: tuple[object, ...]¶
テンプレート内で補間されるすべての値のタプル。
>>> cheese = 'Camembert' >>> template = t'Ah! We do have {cheese}.' >>> template.values ('Camembert',)
valuesタプルの長さは、常にinterpolationsタプルと同じです。 常にtuple(i.value for i in template.interpolations)と等価です。
メソッド
- __new__(*args: str | Interpolation)¶
Templateはリテラル構文で作成するのが一般的ですが、コンストラクタを使って直接作成することもできます。>>> 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, ''), '.']
複数の文字列を続けて渡すと、
strings属性内の 1 つの値に連結されます。 例えば次のコードは、最終的に文字列が 1 つだけになるTemplateを作成します。>>> from string.templatelib import Template >>> template = Template('Ah! We do have ', 'Camembert', '.') >>> template.strings ('Ah! We do have Camembert.',)
複数の補間を続けて渡すと、それぞれ別の補間として扱われ、間に空文字列が挿入されます。 例えば次のコードは、
strings属性に空文字列のプレースホルダーを持つテンプレートを作成します。>>> from string.templatelib import Interpolation, Template >>> template = Template( ... Interpolation('Camembert', 'cheese'), ... Interpolation('.', 'punctuation'), ... ) >>> template.strings ('', '', '')
- iter(template)
テンプレートを反復処理し、空でない各文字列と
Interpolationを正しい順序で yield します。>>> cheese = 'Camembert' >>> list(t'Ah! We do have {cheese}.') ['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']
注意
反復処理には空文字列は 含まれません。
>>> 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
このテンプレートを別のテンプレートと連結し、新しい
Templateインスタンスを返します。>>> cheese = 'Camembert' >>> list(t'Ah! ' + t'We do have {cheese}.') ['Ah! We do have ', Interpolation('Camembert', 'cheese', None, ''), '.']
Templateとstrの連結はサポート していません。 文字列を静的な文字列として扱うのか、補間として扱うのかが不明確なためです。Templateと文字列を連結するには、文字列を直接Templateで包んで静的な文字列として扱うか、Interpolationを使って動的な部分として扱ってください。>>> 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¶
Interpolation型は、テンプレート文字列内の式を表します。 イミュータブルであり、補間オブジェクトの属性には再代入できません。補間オブジェクトはパターンマッチングをサポートしているため、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
補間オブジェクトは、その値の型を指定できる ジェネリック型 です。
属性
- expression: str¶
For interpolations created by t-string literals,
expressionis the expression text found inside the curly brackets ({&}), including any whitespace, excluding the curly brackets themselves, and ending before the first!,:, or=if any is present. For manually created interpolations,expressionis the arbitrary string provided when constructing the interpolation instance.手動で作成する
Interpolationインスタンスのexpressionフィールドには、有効な Python の式か空文字列を使うことを推奨します。 ただし、実行時には強制されません。>>> t'{1 + 2}'.interpolations[0].expression '1 + 2'
- conversion: Literal['a', 'r', 's'] | None¶
値に適用する変換、または
None。conversionは、値に適用する省略可能な変換です。>>> t'{1 + 2!a}'.interpolations[0].conversion 'a'
注釈
f 文字列では変換が自動的に適用されますが、t 文字列では
Templateを 処理する コードが、conversionの解釈方法と適用するかどうかを決めることが想定されています。 便利な機能として、convert()関数で f 文字列の変換の動作を再現できます。
- format_spec: str¶
値に適用する書式指定。
format_specは、値を表示する際の書式指定として使う、省略可能な任意の文字列です。>>> t'{1 + 2:.2f}'.interpolations[0].format_spec '.2f'
注釈
f 文字列では
format()プロトコルを通じて書式指定が自動的に適用されますが、t 文字列では補間を 処理する コードが、書式指定の解釈方法と適用するかどうかを決めることが想定されています。 そのため、補間のformat_specには、format()プロトコルに従わないものも含め、任意の文字列を指定できます。
メソッド