これを行うための良いイディオムは何ですか:
それ以外の:
print "%s is a %s %s that %s" % (name, adjective, noun, verb)
次のような効果が得られるようにしたい:
print "{name} is a {adjective} {noun} that {verb}"
"{name} is a {adjective} {noun} that {verb}".format(**locals())
locals()
現在の名前空間への参照を (辞書として) 与えます。**locals()
その辞書をキーワード引数 ( f(**{'a': 0, 'b': 1})
is f(a=0, b=1)
) に展開します。.format()
は「新しい文字列の書式設定」であり、さらに多くのことができます (たとえば{0.name}
、最初の位置引数の name 属性)。または、string.template
(繰り返しますが、冗長な{'name': name, ...}
dict リテラルを避けたい場合はローカルを使用します)。
Python 3.6 以降、f-strings と呼ばれるこの構文を使用できるようになりました。これは、9 年前の提案と非常によく似ています。
print(f"{name} is a {adjective} {noun} that {verb}")
f-strings またはフォーマットされた文字列リテラルは、それらが使用されているスコープの変数、または他の有効な Python 式を使用します。
print(f"1 + 1 = {1 + 1}") # prints "1 + 1 = 2"
使用するstring.Template
>>> from string import Template
>>> t = Template("$name is a $adjective $noun that $verb")
>>> t.substitute(name="Lionel", adjective="awesome", noun="dude", verb="snores")
'Lionel is a awesome dude that snores'
Python 2 の場合:
print name,'is a',adjective,noun,'that',verb
Python 3 の場合、括弧を追加します。
print(name,'is a',adjective,noun,'that',verb)
文字列に保存する必要がある場合は、+
演算子で連結し、スペースを挿入する必要があります。 パラメータの末尾にカンマがない限りprint
、空白を挿入します。カンマがある場合、改行は無視されます。,
文字列変数に保存するには:
result = name+' is a '+adjective+' '+noun+' that '+verb