Führt Python eine variable Interpolation ähnlich wie "string # {var}" in Ruby durch?
In Python, es ist mühsam zu schreiben:
print "foo is" + bar + '.'
Kann ich etwas tun, wie dieses in Python?
print "foo is #{bar}."
InformationsquelleAutor der Frage mko | 2012-08-03
Du musst angemeldet sein, um einen Kommentar abzugeben.
Python 3.6+ hat variable interpolation - prepend ein
f
zu Ihrem string:Für die Versionen Python unterhalb dieses (Python-2 - 3.5), die Sie verwenden können
str.format
zu übergeben Variablen:InformationsquelleAutor der Antwort Sean Vieira
Python-3.6
hat Literale string-interpolation mit f-Saiten:InformationsquelleAutor der Antwort AXO
Python 3.6 hat eingeführt, die f-Saiten:
Alte Antwort:
Seit version 3.2 Python hat
str.format_map
die zusammen mitlocals()
oderglobals()
ermöglicht Ihnen die schnelle:InformationsquelleAutor der Antwort warvariuc
Habe ich gelernt, das folgende Verfahren aus Python Essential Reference:
Dies ist sehr nützlich, wenn wir wollen, zu finden, zu viele Variablen im Format string:
"{x}{y}".format(x=x, y=y)
und"%(x)%(y)" % {"x": x, "y": y}
)."{}{}".format(x, y)
"{0}{1}".format(x, y)
und"%s%s" % (x, y)
).InformationsquelleAutor der Antwort dkim
String-Formatierung
InformationsquelleAutor der Antwort Josiah
Ich bevorzuge diese Methode, da Sie nicht haben, zu wiederholen, sich durch Verweis auf die variable zweimal:
InformationsquelleAutor der Antwort Chris Johnson
Gibt es einen großen Unterschied zwischen dieser in Ruby:
Und diese in Python:
In der Ruby-Beispiel
bar
ist bewertetIn der Python-Beispiel
bar
ist einfach nur ein Schlüssel zum WörterbuchIn dem Fall, dass Sie nur mit Variablen, die Verhalten sich mehr oder weniger die gleichen, aber im Allgemeinen, Konvertierung, Ruby, Python ist nicht ganz so einfach
InformationsquelleAutor der Antwort John La Rooy
Ja, absolut. Python, meiner Meinung nach, hat große Unterstützung für string-Formatierung, Ersatz-und Betreiber.
Dieser hilfreich sein könnten:
http://docs.python.org/library/stdtypes.html#string-formatting-operations
InformationsquelleAutor der Antwort Edmon
Fast jede andere Antwort nicht für mich arbeiten. Wahrscheinlich ist es weil ich bin auf Python ist3.5. Die einzige Sache, die funktioniert hat, ist:
InformationsquelleAutor der Antwort valk