Una str in Python è una sequenza immutabile di punti di codice Unicode.
Questi possono includere lettere, segni diacritici, caratteri di posizionamento, numeri, simboli di valuta, emoji, punteggiatura, caratteri di spazio e di fine riga e molto altro.
Per un approfondimento su quali informazioni codifica una stringa (o, «come fa un computer a sapere come tradurre zeri e uno in lettere?»), questo post del blog è sempre di grande aiuto.
Anche la documentazione di Python fornisce un HOWTO unicode molto dettagliato che tratta il supporto di Python per la specifica Unicode nei moduli str, bytes e re, alcune considerazioni sui locale e diversi problemi comuni di codifica e traduzione.
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>).
È possibile fare riferimento ai singoli punti di codice (stringhe di lunghezza 1) tramite un numero di 0-based index da sinistra, oppure di -1-based index da destra.
Le stringhe possono essere concatenate con <str> + <other str> o <str>.join(<iterable>) e divise tramite <str>.split(<separator>).
Offrono inoltre molte altre opzioni di formattazione, composizione e interpolazione.
Un letterale str può essere dichiarato usando virgolette singole ' o doppie ". Il carattere di escape \ è disponibile quando serve.
>>> single_quoted = 'These allow "double quoting" without "escape" characters.'
>>> double_quoted = "These allow embedded 'single quoting', so you don't have to use an 'escape' character."
Le stringhe multi-riga si dichiarano con ''' o """.
>>> triple_quoted = '''Three single quotes or "double quotes" in a row allow for multi-line string literals.
Line break characters, tabs and other whitespace is fully supported. Remember - The escape "\" character is also available if needed (as can be seen below).
You\'ll most often encounter multi-line strings as "doc strings" or "doc tests" written just below the first line of a function or class definition.
They\'re often used with auto documentation ✍ tools.
'''
Il costruttore str(<object>) può essere usato per creare/forzare stringhe a partire da altri oggetti:
>>> my_number = 42
>>> str(my_number)
...
"42"
Il costruttore str(<object>) può essere usato per forzare/convertire in stringhe, ma non itererà né scompatterà un oggetto.
Questo comportamento è diverso da quello dei costruttori di altri tipi di dato come list(), set(), dict() o tuple(), e può dare risultati sorprendenti.
>>> numbers = [1,3,5,7]
>>> str(numbers)
...
'[1,3,5,7]'
È possibile fare riferimento ai punti di codice all'interno di una str tramite un numero di 0-based index da sinistra:
creative = '창의적인'
>>> creative[0]
'창'
>>> creative[2]
'적'
>>> creative[3]
'인'
L'indicizzazione funziona anche da destra, a partire da un -1-based index:
creative = '창의적인'
>>> creative[-4]
'창'
>>> creative[-2]
'적'
>>> creative[-1]
'인'
In Python non esiste un tipo separato «carattere» o «rune», quindi indicizzare una stringa produce una nuova str di lunghezza 1:
>>> website = "exercism"
>>> type(website[0])
<class 'str'>
>>> len(website[0])
1
>>> website[0] == website[0:1] == 'e'
True
Le sottostringhe possono essere selezionate tramite la slice notation, usando <str>[<start>:<stop>:<step>] per produrre una nuova stringa.
I risultati escludono l'indice stop.
Se non viene fornito start, l'indice iniziale sarà 0.
Se non viene fornito stop, l'indice stop sarà la fine della stringa.
moon_and_stars = '🌟🌟🌙🌟🌟⭐'
>>> moon_and_stars[1:4]
'🌟🌙🌟'
>>> moon_and_stars[:3]
'🌟🌟🌙'
>>> moon_and_stars[3:]
'🌟🌟⭐'
>>> moon_and_stars[:-1]
'🌟🌟🌙🌟🌟'
>>> moon_and_stars[:-3]
'🌟🌟🌙'
Le stringhe possono anche essere spezzate in stringhe più piccole tramite <str>.split(<separator>), che restituirà una list di sottostringhe.
Usare <str>.split() senza argomenti divide la stringa sui caratteri di spaziatura.
>>> cat_ipsum = "Destroy house in 5 seconds command the hooman."
>>> cat_ipsum.split()
...
['Destroy', 'house', 'in', '5', 'seconds', 'command', 'the', 'hooman.']
>>> cat_words = "feline, four-footed, ferocious, furry"
>>> cat_words.split(',')
...
['feline', ' four-footed', ' ferocious', ' furry']
>>> colors = """red,
orange,
green,
purple,
yellow"""
>>> colors.split(',\n')
['red', 'orange', 'green', 'purple', 'yellow']
Le stringhe possono essere concatenate usando l'operatore +.
Conviene usare questo metodo con moderazione, perché non è molto efficiente né facile da mantenere.
language = "Ukrainian"
number = "nine"
word = "дев'ять"
sentence = word + " " + "means" + " " + number + " in " + language + "."
>>> print(sentence)
...
"дев'ять means nine in Ukrainian."
Se una list, una tuple, un set o un'altra collezione di singole stringhe deve essere combinata in un'unica str, <str>.join(<iterable>) è un'opzione migliore:
# str.join() makes a new string from the iterables elements.
>>> chickens = ["hen", "egg", "rooster"] # Lists are iterable.
>>> ' '.join(chickens)
'hen egg rooster'
# Any string can be used as the joining element.
>>> ' :: '.join(chickens)
'hen :: egg :: rooster'
>>> ' 🌿 '.join(chickens)
'hen 🌿 egg 🌿 rooster'
# Any iterable can be used as input.
>>> flowers = ("rose", "daisy", "carnation") # Tuples are iterable.
>>> '*-*'.join(flowers)
'rose*-*daisy*-*carnation'
>>> flowers = {"rose", "daisy", "carnation"} # Sets are iterable, but output order is not guaranteed.
>>> '*-*'.join(flowers)
'rose*-*carnation*-*daisy'
>>> phrase = "This is my string" # Strings are iterable, but be careful!
>>> '..'.join(phrase)
'T..h..i..s.. ..i..s.. ..m..y.. ..s..t..r..i..n..g'
# Separators are inserted **between** elements, but can be any string (including spaces).
# This can be exploited for interesting effects.
>>> under_words = ['under', 'current', 'sea', 'pin', 'dog', 'lay']
>>> separator = ' ⤴️ under' # Note the leading space, but no trailing space.
>>> separator.join(under_words)
'under ⤴️ undercurrent ⤴️ undersea ⤴️ underpin ⤴️ underdog ⤴️ underlay'
# The separator can be composed different ways, as long as the result is a string.
>>> upper_words = ['upper', 'crust', 'case', 'classmen', 'most', 'cut']
>>> separator = ' 🌟 ' + upper_words[0] # This becomes one string, similar to ' ⤴️ under'.
>>> separator.join(upper_words)
'upper 🌟 uppercrust 🌟 uppercase 🌟 upperclassmen 🌟 uppermost 🌟 uppercut'
Le stringhe supportano tutte le operazioni comuni sulle sequenze.
È possibile iterare i singoli punti di codice in un ciclo tramite for item in <str>.
È possibile iterare gli indici con gli elementi in un ciclo tramite for index, item in enumerate(<str>).
>>> exercise = 'လေ့ကျင့်'
# Note that there are more code points than perceived glyphs or characters.
# Care should be used when iterating over languages that use
# combining characters, or when dealing with emoji.
>>> for code_point in exercise:
... print(code_point)
...
လ
ေ
့
က
ျ
င
်
့
# Using enumerate will give both the value and index position of each element.
>>> for index, code_point in enumerate(exercise):
... print(index, ": ", code_point)
...
0 : လ
1 : ေ
2 : ့
3 : က
4 : ျ
5 : င
6 : ်
7 : ့
Python offre un ricco insieme di metodi per le stringhe che possono aiutare con la ricerca, la pulizia, la suddivisione, la trasformazione, la traduzione e molte altre operazioni. Una selezione di questi metodi è trattata in un altro esercizio.
Python offre anche un ricco insieme di strumenti per la formattazione e l'interpolazione delle stringhe, oltre a un'elaborazione del testo più sofisticata tramite i moduli re (espressioni regolari), difflib (confronto di sequenze) e textwrap. Per una splendida introduzione alla formattazione delle stringhe in Python, vedi questo post su Real Python. Per un'introduzione ai metodi delle stringhe, vedi Strings and Character Data in Python sullo stesso sito.
Oltre a str (una sequenza di testo), Python ha i corrispondenti tipi di sequenza binaria riassunti in binary data services: bytes (una sequenza binaria), bytearray e memoryview per archiviare e gestire in modo efficiente dati binari.
Inoltre, gli Streams permettono di inviare e ricevere dati binari su una connessione di rete senza usare callback.