は、それを書くのは面倒です:PythonにはRubyの "string#{var}"のような変数補間がありますか? Pythonで
print "foo is" + bar + '.'
私はpythonでこのような何かを行うことができますか?
print "foo is #{bar}."
は、それを書くのは面倒です:PythonにはRubyの "string#{var}"のような変数補間がありますか? Pythonで
print "foo is" + bar + '.'
私はpythonでこのような何かを行うことができますか?
print "foo is #{bar}."
Pythonは変数展開を行いません - それは、明示的ではなく、暗黙的です。
ただし、変数に渡すstr.format
を使用することができます:私はPython Essential Referenceから、次の技術を学んだ
# Rather than this:
puts "foo is #{bar}"
# You would do this:
print "foo is {}".format(bar)
# Or this:
print "foo is {bar}".format(bar=bar)
# Or this:
print "foo is %s" % (bar,)
# Or even this:
print "foo is %(bar)s" % {"bar": bar}
第3のものはきれいに見えますが、私はこのように推奨されない方法を覚えていますか?本当? – mko
また、怠け者の 'print 'fooは%(bar)s"%locals() 'です。 –
@yozloy - それはPython 3で非難されています(私はそれを理解しています)。 –
はい、絶対に。 Pythonは、私の意見では、文字列の書式設定、置換え、演算子を非常にサポートしています。
これが役に立つかもしれません:
http://docs.python.org/library/stdtypes.html#string-formatting-operations
>>> bar = 1
>>> print "foo is {}.".format(bar)
foo is 1.
:
>>> bar = "baz"
>>> print "foo is {bar}.".format(**vars())
foo is baz.
我々は、多くの変数を参照したいときにこれは非常に便利です書式設定文字列:
"{x}{y}".format(x=x, y=y)
および"%(x)%(y)" % {"x": x, "y": y}
)と比較してください。"{}{}".format(x, y)
、"{0}{1}".format(x, y)
、"%s%s" % (x, y)
など) 。であっても、' 'print 'とfooは#{bar}それはバーで渡す奇妙な方法です...かなり素敵ですが、それはより密接にルビーの方法に従います。 – Josiah
これは、オブジェクトを使って作業している場合に最適なソリューションのようです。たとえば、urllib2.HTTPErrorを報告している場合、HTTPエラー:{error.code} {error.msg} "を実行できます。format(** vars())'これは ' * locals()) ' –
Rubyでこの間には大きな違いがあります:
print "foo is #{bar}."
はまた、これらはPythonで:
print "foo is {bar}".format(bar=bar)
Rubyの例では、ははbar
はPythonのISNにルビーを変換し、あなただけの振る舞い多かれ少なかれ同じ変数を使用している辞書場合
にちょうどキーであるが、一般的には、Pythonの例では
評価され、かなり単純です。
Python 3。バージョン3.2 Pythonは一緒にlocals()
かglobals()
とあなたが速く行うことができますstr.format_map
を持っているので
:
print(f"foo is {bar}.")
旧答え:6はintroduced f-stringsを持って
Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
>>> bar = "something"
>>> print("foo is {bar}".format_map(locals()))
foo is something
>>>
のPython 3.6 意志はliteral string interpolationであり、f -strings:
print(f"foo is {bar}.")
誰かが不思議だった場合:これは 'rf 'fooのような生の文字列で、{bar}" 'です。 –
[Pythonで文字列にフォーマット番号]の可能複製(http://stackoverflow.com/questions/22617/format-numbers-to-strings-in-python) –
私が思う私は、解決策を見つけましたか、あなたはそれをチェックしますか? http://stackoverflow.com/questions/16504732/how-could-i-make-my-python-string-interpolation-implementation-work-accross-impo – SalchiPapa
[Rubyの文字列に相当するPythonが存在しますか補間?](https://stackoverflow.com/questions/4450592/is-there-a-python-equivalent-to-rubys-string-interpolation) – josemigallas