Cómo imprimir múltiples argumentos en Python
- Requisito
- Soluciones - Imprimir múltiples argumentos en Python
- Método de Python 3.6 Only - formato de f-string
Te mostraremos cómo imprimir múltiples argumentos en Python 2 y 3.
Requisito
Suponga que tiene dos variables
city = "Amsterdam"
country = "Netherlands"
Por favor, escriba en letra de molde la cadena que incluye los argumentos city
y country
, como se indica a continuación
City Amsterdam is in the country Netherlands
Soluciones - Imprimir múltiples argumentos en Python
Soluciones para Python 2 y 3
1. Pasar los valores como parámetros
# Python 2
>>> print "City", city, 'is in the country', country
# Python 3
>>> print("City", city, 'is in the country', country)
2. Utilizar el formato de cadena
Hay tres métodos de formato de cadena que pueden pasar argumentos a la cadena.
- Opción secuencial
# Python 2
>>> print "City {} is in the country {}".format(city, country)
# Python 3
>>> print("City {} is in the country {}".format(city, country))
-
Formato con números
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))
-
Formato con nombres explícitos
# 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. Pasar los argumentos como una tupla
# 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étodo de Python 3.6 Only - formato de f-string
Python introduce un nuevo tipo de cadena literals-f-strings
a partir de la versión 3.6. Es similar al método de formateo de cadenas 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