Rubyの例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功したPython文字列の連結は、私には一見冗長に見えます。
Rubyの例:
name = "Spongebob Squarepants"
puts "Who lives in a Pineapple under the sea? \n#{name}."
成功したPython文字列の連結は、私には一見冗長に見えます。
Python 3.6は、Rubyの文字列補間と同様のリテラル文字列補間を追加します。そのバージョンのPython(2016年末までにリリースされる予定)以降、「f-strings」に式を含めることができるようになります。
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
最近のPythonバージョンのメソッドを使用した同じコード.format()
は次のようになります。
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"))
Python 2.6.X以降、次のものを使用することをお勧めします。
"my {0} string: {1}".format("cool", "Hello there!")
Pythonで文字列補間を可能にするinterpyパッケージを開発しました。
を介してインストールするだけpip install interpy
です。次に、ファイルの先頭に行を追加し# coding: interpy
ます。
例:
#!/usr/bin/env python
# coding: interpy
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."
Pythonの文字列補間は、Cのprintf()に似ています。
試してみると:
name = "SpongeBob Squarepants"
print "Who lives in a Pineapple under the sea? %s" % name
タグ%s
は変数に置き換えられname
ます。印刷関数タグを確認する必要があります:http://docs.python.org/library/functions.html
文字列補間は、PEP498で指定されているPython3.6に含まれる予定です。これを行うことができます:
name = 'Spongebob Squarepants'
print(f'Who lives in a Pineapple under the sea? \n{name}')
私はスポンジボブが嫌いなので、これを書くのは少し苦痛でした。:)
あなたもこれを持つことができます
name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n{name}.".format(name=name)
import inspect
def s(template, **kwargs):
"Usage: s(string, **locals())"
if not kwargs:
frame = inspect.currentframe()
try:
kwargs = frame.f_back.f_locals
finally:
del frame
if not kwargs:
kwargs = globals()
return template.format(**kwargs)
使用法:
a = 123
s('{a}', locals()) # print '123'
s('{a}') # it is equal to the above statement: print '123'
s('{b}') # raise an KeyError: b variable not found
PS:パフォーマンスが問題になる可能性があります。これは、実稼働ログではなく、ローカルスクリプトに役立ちます。
複製:
古いPython(2.4でテスト済み)の場合、最上位のソリューションが道を示します。あなたはこれを行うことができます:
import string
def try_interp():
d = 1
f = 1.1
s = "s"
print string.Template("d: $d f: $f s: $s").substitute(**locals())
try_interp()
そして、あなたは
d: 1 f: 1.1 s: s
Python 3.6以降には、f文字列を使用したリテラル文字列補間があります。
name='world'
print(f"Hello {name}!")