Come stampare più argomenti in Python

Jinku Hu 30 gennaio 2023
  1. Requisito
  2. Soluzioni - Stampa più argomenti in Python
  3. Python 3.6 Solo metodo - formattazione f-stringa
Come stampare più argomenti in Python

Vi mostreremo come stampare più argomenti in Python 2 e 3.

Requisito

Supponiamo di avere due variabili

city = "Amsterdam"
country = "Netherlands"

Si prega di stampare la stringa che include entrambi gli argomenti city e country, come segue

City Amsterdam is in the country Netherlands

Soluzioni - Stampa più argomenti in Python

Soluzioni Python 2 e 3

1. Passare i valori come parametri

# Python 2
>>> print "City", city, 'is in the country', country

# Python 3
>>> print("City", city, 'is in the country', country)

2. Utilizzare la formattazione delle stringhe

Ci sono tre metodi di formattazione delle stringhe che potrebbero passare argomenti alla stringa.

  • Opzione sequenziale
# Python 2
>>> print "City {} is in the country {}".format(city, country)

# Python 3
>>> print("City {} is in the country {}".format(city, country))
  • Formattazione con i numeri

    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))
    
  • Formattazione con nomi espliciti

    # 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. Passare argomenti come 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))

Python 3.6 Solo metodo - formattazione f-stringa

Python introduce un nuovo tipo di stringa letterale-f-corde dalla versione 3.6. È simile al metodo di formattazione delle stringhe str.format().

# Only from Python 3.6
>>> print(f"City {city} is in the country {country}")
Autore: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

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

Articolo correlato - Python Print