Lesson 18 +10 XP

Slicing Strings

Slicing Strings

Slicing pulls out a part of a string using a range of indexes.

Basic slice: start to end

b = "Hello, World!"
print(b[2:5])  # llo

[2:5] means: start at index 2, stop before index 5. So you get indexes 2, 3, and 4.

Slice from the start

Leaving the start empty begins at index 0:

b = "Hello, World!"
print(b[:5])  # Hello

Slice to the end

Leaving the end empty goes all the way to the last character:

print(b[7:])  # World!

Negative indexes

Count from the end. -1 is the last character:

print(b[-5:-2])  # orl

b[-5:] gives the last five characters: orld!

Step (extra parameter)

A third number is the step:

print(b[::2])  # every second character

String slice returns a new string

Slicing never changes the original; it gives you a fresh copy of that part.

TL;DR

  • s[start:end]: from start up to (not including) end.
  • s[:n] starts at 0; s[n:] goes to the end.
  • Negative indexes count from the right.
  • A third value adds a step.