Como imprimir múltiplos argumentos em Python
- Requisito
- Soluções - Imprimir múltiplos argumentos em Python
- Python 3.6 Somente Método - formatação f-string
Vamos mostrar-lhe como imprimir múltiplos argumentos em Python 2 e 3.
Requisito
Suponha que você tenha duas variáveis
city = "Amsterdam"
country = "Netherlands"
Por favor, imprima a string que inclui os argumentos city
e country
, como abaixo
City Amsterdam is in the country Netherlands
Soluções - Imprimir múltiplos argumentos em Python
Soluções Python 2 e 3
1. Passar 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. Use a formatação de strings
Há três métodos de formatação de string que poderiam passar argumentos para a string.
- Opção seqüencial
# Python 2
>>> print "City {} is in the country {}".format(city, country)
# Python 3
>>> print("City {} is in the country {}".format(city, country))
- Formatação com 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))
- Formatação com nomes 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. Passar argumentos como um 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))
Python 3.6 Somente Método - formatação f-string
Python introduz um novo tipo de string literals-f-strings
a partir da versão 3.6. Ele é similar ao método de formatação de strings str.format()
.
# Only from Python 3.6
>>> print(f"City {city} is in the country {country}".format(country=country, city=city))