Ruby の文字列補間に相当する Python はありますか? 質問する

Ruby の文字列補間に相当する Python はありますか? 質問する

Rubyの例:

name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."

成功した Python 文字列連結は、私にとっては冗長に思えます。

ベストアンサー1

Python 3.6では、リテラル文字列の補間Rubyの文字列補間に似ています。Pythonのそのバージョン(2016年末までにリリース予定)から、「f文字列」に式を含めることができるようになります。例:

name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")

3.6より前では、これに最も近いのは

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())

この%演算子は、文字列補間Python では、最初のオペランドは補間される文字列で、2 番目のオペランドは「マッピング」を含むさまざまな型を持つことができ、フィールド名を補間される値にマッピングします。ここでは、ローカル変数の辞書を使用して、locals()フィールド名をnameローカル変数としてその値にマッピングしました。

.format()最近の Python バージョンのメソッドを使用した同じコードは次のようになります。

name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))

また、string.Templateクラス:

tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))

おすすめ記事