Formattazione posizionale

Espressioni regolari in Python

Maria Eugenia Inzaugarat

Data scientist

Cos'è la formattazione di stringhe?

  • Interpolazione di stringhe

  • Inserisci una stringa o variabile in un testo predefinito:

custom_string = "String formatting"
print(f"{custom_string} is a powerful technique")
String formatting is a powerful technique
  • Usi:
    • Titolo in un grafico
    • Mostrare un messaggio o errore
    • Passare un testo a una funzione
Espressioni regolari in Python

Metodi di formattazione

  • Formattazione posizionale
  • f-string (stringhe formattate)
  • Metodo template
Espressioni regolari in Python

Formattazione posizionale

  • Placeholder sostituito dal valore

  • str.format()

 

print("Machine learning provides {} the ability to learn {}".format("systems", "automatically"))
Machine learning provides systems the ability to learn automatically
Espressioni regolari in Python

Formattazione posizionale

  • Usa variabili sia per la stringa base sia per i valori passati al metodo
my_string = "{} rely on {} datasets"
method = "Supervised algorithms"
condition = "labeled"
print(my_string.format(method, condition))
Supervised algorithms rely on labeled datasets
Espressioni regolari in Python

Riordinare i valori

  • Inserisci un indice nei placeholder per riordinare i valori
print("{} has a friend called {} and a sister called {}".format("Betty", "Linda", "Daisy"))
Betty has a friend called Linda and a sister called Daisy

 

print("{2} has a friend called {0} and a sister called {1}".format("Betty", "Linda", "Daisy"))
Daisy has a friend called Betty and a sister called Linda
Espressioni regolari in Python

Placeholder nominati

  • Specifica un nome per i placeholder
tool="Unsupervised algorithms"
goal="patterns"
print("{title} try to find {aim} in the dataset".format(title=tool, aim=goal))
Unsupervised algorithms try to find patterns in the dataset
Espressioni regolari in Python

Placeholder nominati

my_methods = {"tool": "Unsupervised algorithms", "goal": "patterns"}
print('{data[tool]} try to find {data[goal]} in the dataset'.format(data=my_methods))
Unsupervised algorithms try to find patterns in the dataset
Espressioni regolari in Python

Specificatore di formato

  • Specifica il tipo: {index:specifier}
print("Only {0:f}% of the {1} produced worldwide is {2}!".format(0.5155675, "data", "analyzed"))
Only 0.515568% of the data produced worldwide is analyzed!

 

print("Only {0:.2f}% of the {1} produced worldwide is {2}!".format(0.5155675, "data", "analyzed"))
Only 0.52% of the data produced worldwide is analyzed!
Espressioni regolari in Python

Formattare datetime

 

from datetime import datetime
print(datetime.now())
datetime.datetime(2019, 4, 11, 20, 19, 22, 58582)

 

print("Today's date is {:%Y-%m-%d %H:%M}".format(datetime.now()))
Today's date is 2019-04-11 20:20
Espressioni regolari in Python

Passons à la pratique !

Espressioni regolari in Python

Preparing Video For Download...