Le f-string o stringhe formattate in Python sono il nuovo modo per formattare le stringhe. Questa funzionalità è stata introdotta in Python 3.6 con il PEP-498. È anche chiamata interpolarzione letterale delle stringhe.
Perché abbiamo bisogno delle f-string?
Python fornisce vari modi per formattare una stringa. Vediamoli rapidamente e quali sono i problemi che presentano.
-
Formattazione % – ottima per formattazioni semplici, ma supporto limitato per stringhe, solo interi e doppi. Non possiamo usarlo con gli oggetti.
-
Stringhe modello – è molto basico. Le stringhe modello funzionano solo con argomenti di parole chiave come un dizionario. Non ci è permesso chiamare alcuna funzione e gli argomenti devono essere stringhe.
-
Formato della stringa() – La funzione di formattazione della stringa di Python format() è stata introdotta per superare i problemi e le limitate caratteristiche della formattazione con %-formatting e delle stringhe di modello. Tuttavia, è troppo verbosa. Esaminiamo la sua verbosità con un semplice esempio.
>>> età = 4 * 10 >>> 'La mia età è {età}.'.format(età=età) 'La mia età è 40.'
Le f-string di Python funzionano quasi come la funzione format(), ma eliminano tutta la verbosità che la funzione format() ha. Vediamo come possiamo formattare facilmente la stringa sopra usando le f-string.
>>> f'My age is {age}'
'My age is 40.'
Le f-string di Python sono introdotte per avere una sintassi minima per la formattazione delle stringhe. Le espressioni vengono valutate durante l’esecuzione. Se stai utilizzando Python 3.6 o una versione successiva, dovresti utilizzare le f-string per tutte le tue esigenze di formattazione delle stringhe.
Esempi di f-strings in Python
Diamo un’occhiata a un esempio semplice di f-strings.
name = 'Pankaj'
age = 34
f_string = f'My Name is {name} and my age is {age}'
print(f_string)
print(F'My Name is {name} and my age is {age}') # f and F are same
name = 'David'
age = 40
# La f-string è già valutata e non cambierà ora
print(f_string)
Output:
My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34
My Name is Pankaj and my age is 34
Python esegue le istruzioni una per una e una volta che le espressioni f-string sono valutate, non cambiano anche se il valore dell’espressione cambia. Ecco perché nei frammenti di codice sopra, il valore della f-string rimane lo stesso anche dopo che le variabili ‘name’ e ‘age’ sono cambiate nella parte successiva del programma.
1. f-strings con espressioni e conversioni
Possiamo utilizzare le f-strings per convertire datetime in un formato specifico. Possiamo anche eseguire espressioni matematiche nelle f-strings.
from datetime import datetime
name = 'David'
age = 40
d = datetime.now()
print(f'Age after five years will be {age+5}') # age = 40
print(f'Name with quotes = {name!r}') # name = David
print(f'Default Formatted Date = {d}')
print(f'Custom Formatted Date = {d:%m/%d/%Y}')
Output:
Age after five years will be 45
Name with quotes = 'David'
Default Formatted Date = 2018-10-10 11:47:12.818831
Custom Formatted Date = 10/10/2018
2. Le f-strings supportano le stringhe “raw”
Possiamo creare stringhe “raw” anche utilizzando le f-strings.
print(f'Default Formatted Date:\n{d}')
print(fr'Default Formatted Date:\n {d}')
Output:
Default Formatted Date:
2018-10-10 11:47:12.818831
Default Formatted Date:\n 2018-10-10 11:47:12.818831
3. f-string con oggetti e attributi
Possiamo accedere anche agli attributi degli oggetti nelle f-stringhe.
class Employee:
id = 0
name = ''
def __init__(self, i, n):
self.id = i
self.name = n
def __str__(self):
return f'E[id={self.id}, name={self.name}]'
emp = Employee(10, 'Pankaj')
print(emp)
print(f'Employee: {emp}\nName is {emp.name} and id is {emp.id}')
Output:
E[id=10, name=Pankaj]
Employee: E[id=10, name=Pankaj]
Name is Pankaj and id is 10
4. f-string che richiamano funzioni
Possiamo anche chiamare funzioni nel formato delle f-stringhe.
def add(x, y):
return x + y
print(f'Sum(10,20) = {add(10, 20)}')
Output: Somma(10,20) = 30
5. f-string con spazi bianchi
Se ci sono spazi bianchi iniziali o finali nell’espressione, vengono ignorati. Se la parte di stringa letterale contiene spazi bianchi, questi vengono preservati.
>>> age = 4 * 20
>>> f' Age = { age } '
' Age = 80 '
6. Espressioni lambda con f-string
Possiamo anche utilizzare espressioni lambda all’interno delle espressioni f-string.
x = -20.45
print(f'Lambda Example: {(lambda x: abs(x)) (x)}')
print(f'Lambda Square Example: {(lambda x: pow(x, 2)) (5)}')
Output:
Lambda Example: 20.45
Lambda Square Example: 25
7. Esempi vari di f-string
Diamo un’occhiata ad alcuni esempi vari di f-string di Python.
print(f'{"quoted string"}')
print(f'{{ {4*10} }}')
print(f'{{{4*10}}}')
Output:
quoted string
{ 40 }
{40}
Ecco tutto per le stringhe formattate di Python, alias f-string.
Puoi controllare lo script Python completo e altri esempi di Python dal nostro Repository GitHub.
Riferimento: PEP-498, Documentazione Ufficiale
Source:
https://www.digitalocean.com/community/tutorials/python-f-strings-literal-string-interpolation