Formato delle stringhe in Python

Completato

Oltre a trasformare il testo e a eseguire operazioni di base, come la corrispondenza e la ricerca, è essenziale formattare il testo quando si presentano le informazioni. Il modo più semplice per presentare informazioni di testo con Python consiste nell'usare la funzione print(). È fondamentale trasformare le informazioni contenute nelle variabili e in altre strutture di dati in stringhe che possano essere usate da print().

In questa unità verranno illustrati diversi modi validi per includere i valori delle variabili nel testo usando Python.

Formattazione del segno di percentuale (%)

Il segnaposto per la variabile nella stringa è %s. Dopo la stringa usare un altro carattere % seguito dal nome della variabile. L'esempio seguente mostra come applicare la formattazione usando il carattere %:

mass_percentage = "1/6"
print("On the Moon, you would weigh about %s of your weight on Earth." % mass_percentage)

Output: On the Moon, you would weigh about 1/6 of your weight on Earth.

L'uso di più valori modifica la sintassi perché le variabili che vengono passate devono essere racchiuse tra parentesi:

print("""Both sides of the %s get the same amount of sunlight, but only one side is seen from %s because the %s rotates around its own axis when it orbits %s.""" % ("Moon", "Earth", "Moon", "Earth"))

Output: Both sides of the Moon get the same amount of sunlight, but only one side is seen from Earth because the Moon rotates around its own axis when it orbits Earth.

Suggerimento

Sebbene questo metodo sia ancora un modo valido per formattare le stringhe, può causare errori e ridurre la chiarezza nel codice quando si gestiscono più variabili. Le altre due opzioni di formattazione descritte in questa unità sono più adatte a questo scopo.

Metodo format()

Il metodo .format() usa le parentesi graffe ({}) come segnaposto all'interno di una stringa e usa l'assegnazione di variabili per sostituire il testo.

mass_percentage = "1/6"
print("On the Moon, you would weigh about {} of your weight on Earth.".format(mass_percentage))

Output: On the Moon, you would weigh about 1/6 of your weight on Earth.

Non è necessario assegnare più volte variabili ripetute, rendendo il metodo meno dettagliato perché è necessario assegnare meno variabili:

mass_percentage = "1/6"
print("""You are lighter on the {0}, because on the {0} you would weigh about {1} of your weight on Earth.""".format("Moon", mass_percentage))

Output: You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

Al posto delle parentesi graffe vuote, la sostituzione prevede l'uso di numeri. {0} indica di usare il primo argomento (indice di zero) di .format(), che in questo caso è Moon. Per la ripetizione semplice {0} funziona bene, ma riduce la leggibilità. Per migliorare la leggibilità, usare gli argomenti di parole chiave in .format() e quindi fare riferimento agli stessi argomenti all'interno di parentesi graffe:

mass_percentage = "1/6"
print("""You are lighter on the {moon}, because on the {moon} you would weigh about {mass} of your weight on Earth.""".format(moon="Moon", mass=mass_percentage))

Output: You are lighter on the Moon, because on the Moon you would weigh about 1/6 of your weight on Earth.

Informazioni sulle stringhe f

A partire dalla versione 3.6 di Python, è possibile usare le stringhe f. Queste stringhe sono simili ai modelli e usano i nomi delle variabili dal codice. L'uso delle stringhe f nell'esempio precedente sarà simile al seguente:

print(f"On the Moon, you would weigh about {mass_percentage} of your weight on Earth.")

Output: On the Moon, you would weigh about 1/6 of your weight on Earth.

Le variabili vengono specificate tra parentesi graffe e la stringa deve usare il prefisso f.

Oltre al fatto che le stringhe f sono meno dettagliate di qualsiasi altra opzione di formattazione, è possibile usare le espressioni all'interno delle parentesi graffe. Queste espressioni possono essere funzioni o operazioni dirette. Ad esempio, se si vuole rappresentare il valore 1/6 come percentuale con una sola posizione decimale, è possibile usare direttamente la funzione round():

print(round(100/6, 1))

Output: 16.7

Con le stringhe f non è necessario assegnare prima un valore a una variabile:

print(f"On the Moon, you would weigh about {round(100/6, 1)}% of your weight on Earth.")

Output: On the Moon, you would weigh about 16.7% of your weight on Earth.

L'uso di un'espressione non richiede una chiamata di funzione. Sono validi anche tutti i metodi di stringa. Ad esempio, la stringa può applicare una combinazione di maiuscole e minuscole specifica per la creazione di un titolo:

subject = "interesting facts about the moon"
heading = f"{subject.title()}"
print(heading)

Output: Interesting Facts About The Moon