Skip to main content
eLearner.app
Module 4 · Lesson 2 of 414/36 in the course~10 min
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

Python
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]

Python
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 2

Unlike indexing, slicing does NOT raise errors if the indices are out of range: it carves out what it can.

The third argument: step

Python
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

Python
len("Python")        # 6
"th" in "Python"     # True
"java" in "Python"   # False

Negative 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

Exercise#python.m4.l2.e1
Attempts: 0Loading…

Given `word = 'PROGRAMMAZIONE'`, obtain its reverse in `reversed_word`. Evaluate `reversed_word`.

Loading editor…
Show hint

word[::-1]

Solution available after 3 attempts

Review exercise

Exercise#python.m4.l2.e2
Attempts: 0Loading…

Given `email = 'ada@example.com'`, extract the domain (everything after '@') into `domain` using slicing after finding the index with .find. Evaluate `domain`.

Loading editor…
Show hint

email[email.find('@') + 1:]

Solution available after 3 attempts

Additional challenge

Exercise#python.m4.l2.e3
Attempts: 0Loading…

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'`).

Loading editor…
Show hint

The first 3 characters are word[:3], the last 3 are word[-3:]. Concatenate the two slices.

Solution available after 3 attempts