HOWTO · Python
Wie man mehrere Argumente in Python ausdruckt
Es zeigt Ihnen, wie Sie mehrere Argumente in Python 2 und 3 drucken können
Auf dieser Seite
Wir zeigen Ihnen, wie Sie mehrere Argumente in Python 2 und 3 drucken können.
Anforderung
Angenommen, Sie haben zwei Variablen
city = "Amsterdam"
country = "Netherlands"
Bitte geben Sie die Zeichenkette aus, die die beiden Argumente city und country enthält, wie unten dargestellt
City Amsterdam is in the country Netherlands
Lösungen - Mehrere Argumente in Python drucken
Python 2 und 3 Lösungen
1. Werte als Parameter übergeben
# Python 2
>>> print "City", city, 'is in the country', country
# Python 3
>>> print("City", city, 'is in the country', country)
2. Stringformatierung verwenden
Es gibt drei Stringformatierungsmethoden, die Argumente an die Zeichenkette übergeben können.
- Sequentielle Option
# Python 2
>>> print "City {} is in the country {}".format(city, country)
# Python 3
>>> print("City {} is in the country {}".format(city, country))
-
Formatierung mit Zahlen
The advantages of this option compared to the last one is that you could reorder the arguments and reuse some arguments as many as possible. Check the examples below,
# Python 2 >> > print "City {1} is in the country {0}, yes, in {0}".format(country, city) # Python 3 >> > print("City {1} is in the country {0}, yes, in {0}".format(country, city)) -
Formatierung mit expliziten Namen
# Python 2 >> > print "City {city} is in the country {country}".format(country=country, city=city) # Python 3 >> > print("City {city} is in the country {country}".format(country=country, city=city))
3. Argumente als Tupel übergeben
# Python 2
>>> print "City %s is in the country %s" %(city, country)
# Python 3
>>> print("City %s is in the country %s" %(city, country))
Python 3.6 Einzige Methode - f-string Formatierung
Python führt ab Version 3.6 einen neuen Typ von String-Literals-f-strings ein. Sie ist ähnlich der Stringformatierungsmethode str.format().
# Only from Python 3.6
>>> print(f"City {city} is in the country {country}")