Ricerca e sostituzione

Espressioni regolari in Python

Maria Eugenia Inzaugarat

Data scientist

Trovare sottostringhe

  • Cerca una sottostringa specifica nella stringa target.

my_string = "Where's Waldo?"
my_string.find("Waldo")
8
my_string.find("Wenda")
-1
Espressioni regolari in Python

Trovare sottostringhe

  • Cerca una sottostringa specifica nella stringa target.

my_string = "Where's Waldo?"
my_string.find("Waldo", 0, 6)
-1
Espressioni regolari in Python

Funzione index

  • Simile a .find(), cerca una sottostringa specifica nella stringa target.

my_string = "Where's Waldo?"
my_string.index("Waldo")
8
my_string.index("Wenda")
File "<stdin>", line 1, in <module> 
ValueError: substring not found
Espressioni regolari in Python

Funzione index

  • Simile a .find(), cerca una sottostringa specifica nella stringa target.

my_string = "Where's Waldo?"
try:
    my_string.index("Wenda")
except ValueError:
      print("Not found")
"Not found"
Espressioni regolari in Python

Contare le occorrenze

  • Restituisce il numero di occorrenze di una sottostringa.

my_string = "How many fruits do you have in your fruit basket?"
my_string.count("fruit")
2
my_string.count("fruit", 0, 16)
1
Espressioni regolari in Python

Sostituire sottostringhe

  • Sostituisci le occorrenze di una sottostringa con un'altra.

my_string = "The red house is between the blue house and the old house"
print(my_string.replace("house", "car"))
The red car is between the blue car and the old car
print(my_string.replace("house", "car", 2))
The red car is between the blue car and the old house
Espressioni regolari in Python

Riepilogo

  • Manipolazione di stringhe:

    • Slice e concatenazione
    • Modifica maiuscole/minuscole
    • Split e join
    • Rimuovere caratteri da inizio e fine
    • Trovare sottostringhe
    • Contare occorrenze
    • Sostituire sottostringhe
Espressioni regolari in Python

Facciamo pratica!

Espressioni regolari in Python

Preparing Video For Download...