Comment imprimer plusieurs arguments en Python
- Exigence
- Solutions - Imprimer plusieurs arguments en Python
-
Méthode Python 3.6 uniquement - formatage de la chaîne de caractères
f
Nous allons vous montrer comment imprimer des arguments multiples en Python 2 et 3.
Exigence
Supposons que vous ayez deux variables
city = "Amsterdam"
country = "Netherlands"
Veuillez imprimer la chaîne qui comprend les deux arguments city
et country
, comme ci-dessous
City Amsterdam is in the country Netherlands
Solutions - Imprimer plusieurs arguments en Python
Solutions Python 2 et 3
1. Passez les valeurs en tant que paramètres
# Python 2
>>> print "City", city, 'is in the country', country
# Python 3
>>> print("City", city, 'is in the country', country)
2. Utiliser le formatage de la chaîne de caractères
Il y a trois méthodes de formatage de chaîne de caractères qui peuvent passer des arguments à la chaîne.
- Option séquentielle
# Python 2
>>> print "City {} is in the country {}".format(city, country)
# Python 3
>>> print("City {} is in the country {}".format(city, country))
-
Formatage avec des chiffres
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))
-
Formatage avec des noms explicites
# 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. Faire passer les arguments comme un tuple
# Python 2
>>> print "City %s is in the country %s" %(city, country)
# Python 3
>>> print("City %s is in the country %s" %(city, country))
Méthode Python 3.6 uniquement - formatage de la chaîne de caractères f
Python introduit un nouveau type de chaînes de caractères littérales-f-strings
à partir de la version 3.6. Il est similaire à la méthode de formatage des chaînes de caractères str.format()
.
# Only from Python 3.6
>>> print(f"City {city} is in the country {country}")
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook