Una str è una sequenza immutabile di punti di codice Unicode.
Può includere lettere, segni diacritici, caratteri di posizionamento, numeri, simboli di valuta, emoji, punteggiatura, spazi e interruzioni di riga, e altro ancora.
Le stringhe implementano tutte le operazioni comuni sulle sequenze e possono essere iterate usando la sintassi for item in <str> o for index, item in enumerate(<str>).
I singoli punti di codice (stringhe di lunghezza 1) possono essere referenziati tramite un numero di 0-based index da sinistra, o un numero di -1-based index da destra.
Le stringhe possono essere concatenate usando <str> + <other str> o <str>.join(<iterable>) e divise tramite <str>.split(<separator>).
Offrono anche molte altre opzioni di formattazione e composizione.
Per lavorare ulteriormente con le stringhe, Python fornisce un ricco insieme di metodi delle stringhe per cercare, pulire, trasformare, tradurre e molte altre operazioni.
Alcuni dei metodi str più comunemente usati includono:
<str>.startswith(<substr>) e <str>.endswith(<substr>)
<str>.title(), <str>.upper()/<str>.lower() e <str>.swapcase()
<str>.strip(<chars>), <str>.lstrip(<chars>) o <str>.rstrip(<chars>)
<str>.replace(<old>, <new>)
Essendo immutabile, il valore di un oggetto str in memoria non può cambiare; i metodi che sembrano modificare una stringa restituiscono una nuova copia o una nuova istanza di quell'oggetto str.
<str>.endswith(<suffix>) restituisce True se la stringa termina con <suffix>, False altrimenti.
>>> 'My heart breaks. 💔'.endswith('💔')
True
>>> 'cheerfulness'.endswith('ness')
True
# Punctuation is part of the string, so needs to be included in any endswith match.
>>> 'Do you want to 💃?'.endswith('💃')
False
>>> 'The quick brown fox jumped over the lazy dog.'.endswith('dog')
False
<str>.title() analizza una stringa e mette in maiuscolo il primo «carattere» di ogni «parola» trovata.
In Python, questo dipende molto dal codec linguistico usato e da come la lingua in questione rappresenta parole e caratteri.
Possono anche esserci regole di locale per una lingua o un set di caratteri.
>>> man_in_hat_th = 'ผู้ชายใส่หมวก'
>>> man_in_hat_ru = 'мужчина в шляпе'
>>> man_in_hat_ko = '모자를 쓴 남자'
>>> man_in_hat_en = 'the man in the hat.'
>>> man_in_hat_th.title()
'ผู้ชายใส่หมวก'
>>> man_in_hat_ru.title()
'Мужчина В Шляпе'
>>> man_in_hat_ko.title()
'모자를 쓴 남자'
>> man_in_hat_en.title()
'The Man In The Hat.'
<str>.strip(<chars>) restituisce una copia della str con i <chars> iniziali e finali rimossi.
I punti di codice specificati in <chars> non sono un prefisso o un suffisso: tutte le combinazioni dei punti di codice verranno rimosse a partire da entrambe le estremità della stringa.
Se non viene specificato nulla per <chars>, verranno rimosse tutte le combinazioni di punti di codice di spaziatura.
Se si vuole rimuovere solo a sinistra o solo a destra, si possono usare <str>.lstrip(<chars>) e <str>.rstrip(<chars>).
# This will remove "https://", because it can be formed from "/stph:".
>>> 'https://unicode.org/emoji/'.strip('/stph:')
'unicode.org/emoji'
# Removal of all whitespace from both ends of the str.
>>> ' 🐪🐪🐪🌟🐪🐪🐪 '.strip()
'🐪🐪🐪🌟🐪🐪🐪'
>>> justification = 'оправдание'
>>> justification.strip('еина')
'оправд'
# Prefix and suffix in one step.
>>> 'unaddressed'.strip('dnue')
'address'
>>> ' unaddressed '.strip('dnue ')
'address'
<str>.replace(<substring>, <replacement substring>) restituisce una copia della stringa con tutte le occorrenze di <substring> sostituite con <replacement substring>.
La citazione usata di seguito è tratta da The Hunting of the Snark di Lewis Carroll
# The Hunting of the Snark, by Lewis Carroll
>>> quote = '''
"Just the place for a Snark!" the Bellman cried,
As he landed his crew with care;
Supporting each man on the top of the tide
By a finger entwined in his hair.
"Just the place for a Snark! I have said it twice:
That alone should encourage the crew.
Just the place for a Snark! I have said it thrice:
What I tell you three times is true."
'''
>>> quote.replace('Snark', '🐲')
...
'\n"Just the place for a 🐲!" the Bellman cried,\n As he landed his crew with care;\nSupporting each man on the top of the tide\n By a finger entwined in his hair.\n\n"Just the place for a 🐲! I have said it twice:\n That alone should encourage the crew.\nJust the place for a 🐲! I have said it thrice:\n What I tell you three times is true."\n'
>>> 'bookkeeper'.replace('kk', 'k k')
'book keeper'
🌟Aggiunto di recente in Python 3.9
Python 3.9 introduce due nuovi metodi delle stringhe che rendono molto più semplice rimuovere prefissi e suffissi.
<str>.removeprefix(<substring>) restituisce la stringa senza il prefisso (string[len(<substring>):]). Se <substring> non è presente, verrà restituita una copia della stringa originale.
# removing a prefix
>>> 'TestHook'.removeprefix('Test')
'Hook'
>>> 'bookkeeper'.removeprefix('book')
'keeper'
<str>.removesuffix(<substring>) restituisce la stringa senza il suffisso (string[:-len(substring)]). Se <substring> non è presente, verrà restituita una copia della stringa originale.
# removing a suffix
>>> 'TestHook'.removesuffix('Hook')
'Test'
>>> 'bookkeeper'.removesuffix('keeper')
'book'
Per altri esempi e metodi, il tutorial informale è un buon punto di partenza. How to Unicode nella documentazione di Python offre molti dettagli su Unicode, codifica, byte e altre considerazioni tecniche per lavorare con le stringhe in Python.
Python supporta anche le espressioni regolari tramite il modulo re, che sarà trattato in un concetto futuro.