複数行の Python 文字列内で変数を使用するためのクリーンな方法を探しています。次の操作を実行したいとします。
string1 = go
string2 = now
string3 = great
"""
I will $string1 there
I will go $string2
$string3
"""
$
Python 構文で変数を示すために Perlに似たものがあるかどうかを確認しています。
そうでない場合、変数を含む複数行の文字列を作成する最もクリーンな方法は何ですか?
ベストアンサー1
一般的な方法は次のformat()
関数です:
>>> s = "This is an {example} with {vars}".format(vars="variables", example="example")
>>> s
'This is an example with variables'
複数行のフォーマット文字列でも問題なく動作します:
>>> s = '''\
... This is a {length} example.
... Here is a {ordinal} line.\
... '''.format(length='multi-line', ordinal='second')
>>> print(s)
This is a multi-line example.
Here is a second line.
変数を含む辞書を渡すこともできます:
>>> d = { 'vars': "variables", 'example': "example" }
>>> s = "This is an {example} with {vars}"
>>> s.format(**d)
'This is an example with variables'
あなたが尋ねたものに最も近いもの(構文の面で)はテンプレート文字列。 例えば:
>>> from string import Template
>>> t = Template("This is an $example with $vars")
>>> t.substitute({ 'example': "example", 'vars': "variables"})
'This is an example with variables'
format()
ただし、この関数はすぐに利用でき、インポート行を必要としないため、より一般的であることを付け加えておきます。