Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
Formattazione delle stringhe
Python utilizza la formattazione delle stringhe in stile C per creare nuove stringhe formattate. L'operatore "%" è utilizzato per formattare un insieme di variabili racchiuse in un "tuple" (una lista di dimensione fissa), insieme a una stringa di formato, che contiene testo normale insieme a "specifier di argomenti", simboli speciali come "%s" e "%d".
Supponiamo che tu abbia una variabile chiamata "name" con il tuo nome utente e desideri stampare un saluto a quell'utente.
Per utilizzare due o più specifier di argomenti, usa un tuple (parentesi):
Qualsiasi oggetto che non sia una stringa può essere formattato utilizzando anche l'operatore %s. La stringa restituita dal metodo "repr" di quell'oggetto è formattata come una stringa. Ad esempio:
Ecco alcuni specifier di argomenti di base che dovresti conoscere:
%s - Stringa (o qualsiasi oggetto con una rappresentazione a stringa, come i numeri)
%d - Numeri interi
%f - Numeri a virgola mobile
%.<numero di cifre>f - Numeri a virgola mobile con un numero fisso di cifre a destra del punto.
%x/%X - Numeri interi in rappresentazione esadecimale (minuscolo/maiuscolo)
Exercise
È necessario scrivere una stringa di formato che stampi i dati usando la seguente sintassi:
Hello John Doe. Your current balance is $53.44.
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!
