Victor Jeman Academy
Python Fundamentals11 min

Strings: indexing and slicing

Reach inside a string by position: indexing, negative indices, length, and slicing.

What You'll Learn

  • Access individual characters in a string using indices
  • Reach the end of a string with negative indices
  • Measure string length with len()
  • Extract portions of strings using slicing
  • Slice with a step to skip or reverse characters

In this lesson

  • Grab one character by position with [i], counting from 0.
  • Reach the end without counting using negative indices like [-1].
  • Measure a string with len().
  • Cut out a chunk with slicing [start:stop], and skip or reverse characters with a step.

A string isn't just a label you print once. You can reach inside it, pull out a single letter, cut a piece from the middle, search it for a word. Every time you create an account somewhere, that's what the platform does with your username: checks its length, grabs the first letter for an avatar, makes sure there's no space or @ where it shouldn't be. The apps you use all day are, under the hood, text machines.

Creare cont — procesare text
PIXEL PORTAL
Creeaza cont nou
pixel_knight
••••••••
Creeaza cont

In the Building strings lesson you learned to glue strings together with + and f-strings. Here you do the opposite: you take strings apart. This lesson is about reaching a character or a chunk by position: indexing and slicing.

Your hero has found an ancient library full of encrypted spells, so this is where you build the puzzle room of the Python Kingdom. Indexing and slicing are how you decode spells, pull halves out of old ones, and forge something new.

Accessing characters (indexing)

text = "gamer_alex"
g
0
a
1
m
2
e
3
r
4
_
5
a
6
l
7
e
8
x
9

Picture a string as a row of boxes, one character per box. Each box has a position number, and the count starts at 0, not 1. That number is the index. The off-by-one feels wrong for about a week, then it's automatic.

Say you have a username stored in a variable:

If you want to find the first letter of this username, you use square brackets with index 0:

Every character sits in a fixed box. The letter g is at position 0, a at 1, m at 2, and so on. Spaces, underscores, anything you can type all take up a box.

Here's where it pays off. Plenty of platforms use the first letter of the username as a default avatar, and that's one line of code:

Avatar: poza vs. initialeapasa pe un profil

Negative indices

text = "tech_wizard"
t
-11
e
-10
c
-9
h
-8
_
-7
w
-6
i
-5
z
-4
a
-3
r
-2
d
-1

What if you want the last character but you don't know how long the string is? You count from the other end with negative indices. Index -1 is the last character, -2 the second to last, and so on.

Say you want to check whether a username ends with a digit. Without negative indices you'd compute the length, subtract one, then index. With -1 you just ask for the last box:

The first character is always at index 0. The last character is always at index -1. You do not need to know the string length to access the end.

String length (len)

len() — lungimea unui stringalege un username
d
a
r
k
_
w
i
z
a
r
d
len("dark_wizard") = 11
perfect

The len() function tells you how many characters a string has. You'll reach for it constantly once you start working with text.

python
username = "dark_wizard"
print(len(username))  # displays: 11

len() counts every character: letters, digits, underscores, spaces. It doesn't skip anything.

One immediate use: check that a username fits the minimum and maximum length the platform allows:

Slicing

text = "shadow_ninja"
s
0
h
1
a
2
d
3
o
4
w
5
_
6
n
7
i
8
n
9
j
10
a
11
text[0:6] = "shadow"

One index gives you one character. When you want a whole chunk, you slice it. The syntax is string[start:stop]: start is the box you begin at, stop is the box you stop before (it's not included). This is worth getting comfortable with, because the exact same syntax also works on lists, which you've already met.

In the example above, username[0:6] grabs positions 0 through 5: six boxes, because box 6 is left out. The "stop before" rule trips up everyone at first, so picture the slice as the boxes between two cuts.

Two shortcuts you'll use a lot. Drop start and Python begins at 0. Drop stop and it runs to the end:

Slicing earns its keep when you want a piece of a username. Plenty of apps show only the first few characters of a name in a notification:

Slicing with a step

Optional deep-dive: skip to the exercises if you just want the basics. Plain [start:stop] covers most of what you will reach for. The step is a neat extra, and [::-1] for reversing is the one piece worth remembering.

So far a slice has two numbers, start and stop. There's a third, the step: [start:stop:step]. The step says how many boxes to jump each time. Leave it out and the step is 1, which is why every slice so far moved one box at a time.

Set the step to 2 and you take every other item, skipping one between each. The same square brackets you used on a string work on a list, because slicing is positional and a list is just another row of boxes:

Drop start and stop, keep the step, and you slice the whole thing at that stride. A step of -1 is the one to remember: it walks the boxes backwards and hands you the sequence reversed, no loop required.

You can combine all three. [1:6:2] starts at box 1, stops before box 6, and jumps two at a time:

That's the full picture: start, stop, step. The same brackets reach into a string or a list, one character or one chunk at a time.

Exercise : Decoding a reversed spell

In the ancient library, spells are written backwards so they cannot be read by intruders. You found the text: "cigam_erif". Write a program that reverses this string character by character (using a while loop and negative indices or starting from the end) to reveal the original spell. Display both the encrypted text and the decoded spell. Build it the manual way first to prove you understand indexing, then notice the solution also shows the [::-1] one-liner that does the same job.

Exercise : Creating a new spell

The hero finds two scrolls with spells: "fire_storm" and "ice_shield". To create a new spell, you must combine the first half of the first spell with the second half of the second one. Use len() and slicing to extract the correct half from each spell, then concatenate them. Display both original spells and the newly created spell.

Exercise : Secret message from ruins

The hero finds an encrypted message on an ancient wall: "AxBxRxAxCxAxDxAxBxRxA". The real message is made up of every other character (positions 0, 2, 4, 6...). Write a program that extracts the secret message by traversing the string with a while loop and a step of 2. Display the encrypted message and the decoded message.

Where this goes next

You can now grab any character or chunk by position: one letter with [i], a piece with [start:stop], every other one with a step. The game file stayed closed this lesson, on purpose. Indexing and slicing are string tools you sharpen here and then point at the game later, so it sits waiting while your kit gets sharper. But a username also needs cleaning and searching: trimming stray spaces, lowercasing for comparison, checking whether it contains an @. That's a different job, transforming and searching the text itself. Next: the string toolbox.

Test Your Knowledge

Check how well you understood the lesson with these 3 questions.

Question 1 of 3

What does "Python"[0] return?