Module lessons (2/4)
Slicing and indexing
In Python, strings are sequences of characters: you can access
individual characters by index and carve out substrings with the slice
syntax [start:stop:step] — exactly as with lists.
Positive and negative indices
s = "Python"
# 0123456
# -6-5-4-3-2-1
s[0] # 'P'
s[5] # 'n'
s[-1] # 'n' (ultimo)
s[-2] # 'o' (penultimo)Out-of-range access raises IndexError.
Slicing [start:stop:step]
s = "Python"
s[0:3] # 'Pyt' indici 0,1,2 (stop ESCLUSO)
s[2:] # 'thon' dal 2 alla fine
s[:3] # 'Pyt' dall'inizio fino al 3 (escluso)
s[:] # 'Python' copia completa
s[-3:] # 'hon' ultimi 3
s[:-2] # 'Pyth' tutto tranne gli ultimi 2Unlike indexing, slicing does NOT raise errors if the indices are out of range: it carves out what it can.
The third argument: step
s = "Python"
s[::2] # 'Pto' salta uno sì uno no
s[1::2] # 'yhn' dispari
s[::-1] # 'nohtyP' INVERSIONE (idiom famoso)s[::-1] is the idiomatic way to reverse a string.
Length and containment
len("Python") # 6
"th" in "Python" # True
"java" in "Python" # FalseNegative indices and step in slicing
The complete syntax of slicing is s[start:stop:step]. If you omit start and stop but set a negative step of -1 (s[::-1]), you reverse the string. The negative index -1 always represents the last character of the string, -2 is the second-to-last, etc.
Try it
Given `word = 'PROGRAMMAZIONE'`, obtain its reverse in `reversed_word`. Evaluate `reversed_word`.
Show hint
word[::-1]
Solution available after 3 attempts
Review exercise
Given `email = 'ada@example.com'`, extract the domain (everything after '@') into `domain` using slicing after finding the index with .find. Evaluate `domain`.
Show hint
email[email.find('@') + 1:]
Solution available after 3 attempts
Additional challenge
Given the string `word = "pythonista"`, use slicing to extract the first 3 characters and the last 3 characters, and concatenate them into a new string `short_word`. Finally, evaluate `short_word` (it should yield `'pytsta'`).
Show hint
The first 3 characters are word[:3], the last 3 are word[-3:]. Concatenate the two slices.
Solution available after 3 attempts