2017-06-14 3 views
-2

Ist es empfehlen einen String formatiert werden:Python3 Druckzeichenfolge Formatierung

var = 'python 3' 
print(f"This is {var}") # prints out This is python 3 

oder

var = 'python 3' 
print("This is", var) 

oder die alte Zeichenfolge Formatierung

var = 'python 3' 
print("This is %s" % var) 

Auch ist print(f"{var}") ein neues Feature Python 3,6? Ich habe SyntaxError: invalid syntax, wenn Sie den gleichen Code in Python 3.5.3 ausführen.

+2

Ja, [f-Strings] (https://www.python.org/dev/peps/pep-0498 /) sind neu in 3.6 – khelwood

+0

* "ist [es] eine neue Funktion für Python 3.6?" * - [ja] (https://docs.python.org/3.6/whatsnew/3.6 .html # pep-498-formatierte Zeichenfolgenliterale. – jonrsharpe

+0

Wenn ich es mit [Online-Compiler] (https://repl.it/languages/python3) in 3.5.2 ausführen, druckt die Ausgabe ohne einen Fehler, so dass ich verwirrt war. – Ricek

Antwort

2

Ist es empfehlenswert ...

niemand etwas erzwingt. Wählen Sie die von Ihnen bevorzugte Option (der zweite Ausdruck formatiert nicht wirklich, es werden einfach mehr Argumente zum Drucken übergeben).

f -Strings wurden eingeführt, um einige Mängel der anderen Formatierungsansätze zu beheben (siehe Rational of PEP 498), wenn Sie die anderen Ansätze gut funktionieren, gibt es keine unmittelbare Notwendigkeit zu wechseln.

ist print(f"{var}") ein neues Feature 3,6

Ja Python, f -Strings sind Python >= 3.6.