f文字列の評価を延期/延期するにはどうすればいいですか? 質問する

f文字列の評価を延期/延期するにはどうすればいいですか? 質問する

私はいくつかのファイルを生成するためにテンプレート文字列を使用していますが、この目的で新しい f 文字列の簡潔さが気に入っています。これにより、以前のテンプレート コードが次のように削減されました。

template_a = "The current name is {name}"
names = ["foo", "bar"]
for name in names:
    print (template_a.format(**locals()))

これで、変数を直接置き換えてこれを行うことができます。

names = ["foo", "bar"]
for name in names:
    print (f"The current name is {name}")

ただし、テンプレートをコードの上位で定義したり、ファイルなどからインポートしたりすることが理にかなっている場合もあります。つまり、テンプレートは書式タグを含む静的な文字列です。インタープリターに文字列を新しい f 文字列として解釈するように指示するには、文字列に何らかの処理を行わなければなりませんが、そのような処理があるかどうかはわかりません。

呼び出しを使用しないように、文字列を取り込んでそれを f 文字列として解釈する方法はありますか.format(**locals())?

理想的には、次のようにコーディングできるようになりたいです... (ここmagic_fstring_functionで、私が理解していない部分が登場します):

template_a = f"The current name is {name}"
# OR [Ideal2] template_a = magic_fstring_function(open('template.txt').read())
names = ["foo", "bar"]
for name in names:
    print (template_a)

...この望ましい出力(ファイルを 2 回読み取らずに)は次のようになります。

The current name is foo
The current name is bar

...しかし、実際に得られる出力は次のようになります。

The current name is {name}
The current name is {name}

参照:文字列リテラルではなく変数で f-string を使用するにはどうすればよいですか?

ベストアンサー1

文字列を f 文字列として評価する(完全な機能を備えた)簡潔な方法は、次の関数を使用することです。

def fstr(template):
    return eval(f'f"""{template}"""')

次に、次の操作を実行します。

template_a = "The current name is {name}"
names = ["foo", "bar"]
for name in names:
    print(fstr(template_a))
# The current name is foo
# The current name is bar

また、他の多くの提案された解決策とは対照的に、次のこともできます。

template_b = "The current name is {name.upper() * 2}"
for name in names:
    print(fstr(template_b))
# The current name is FOOFOO
# The current name is BARBAR

おすすめ記事