Skip to Content
Course content

19: String Indexing and Slicing

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've spent a lot of my career dealing with messy data—logs, CSVs, and API responses where the information isn't neatly handed to you in a dictionary, but rather crammed into a single string. When you're in that situation, you need to be able to reach into a string and pluck out exactly the characters you want. That's where indexing and slicing come in.

Let's imagine we're building a simple log parser. We have a standard log entry format that looks like this: "2023-10-27 [INFO] System boot complete". I need to extract the date and the log level so I can filter them later.

Grabbing the date with basic slicing

Python treats strings like a sequence of characters, and each character has a position, or an "index." The first character is always at index 0. Since I know my date is always the first 10 characters, I can use a slice.

log_entry = "2023-10-27 [INFO] System boot complete"
date_part = log_entry[0:10]
print(date_part) # Output: 2023-10-27

The syntax [start:stop] tells Python: "Start here, and go up to—but not including—the stop index." It feels a bit weird at first that the stop index is exclusive, but it makes the math easier. Since the length of the date is 10, 0:10 gives me exactly 10 characters.

The classic off-by-one mistake

Now I want to grab the log level, which is [INFO]. I can see it starts at index 11. I'll try to grab it by guessing the end index.

# I'm thinking [INFO] is 6 characters long...
log_level = log_entry[11:16]
print(log_level) # Output: [INFO

Wait, I missed the closing bracket. I forgot that the stop index is exclusive, so index 16 is the character after the one I actually want. This is probably the most common mistake you'll make when you start slicing. I just need to bump that number up by one.

# Correcting my mistake
log_level = log_entry[11:17]
print(log_level) # Output: [INFO]

Cleaning up with negative indexing

Sometimes you don't know where a string starts, but you know exactly where it ends. For example, if I wanted to get the last character of the log entry to see if it ends with a period or a newline, I don't want to have to calculate the total length of the string every time.

Python lets us count backward from the end using negative numbers. -1 is the last character, -2 is the second to last, and so on.

# Let's check the very last character
last_char = log_entry[-1]
print(last_char) # Output: e

I can even combine this with slicing. If I wanted to grab everything except the last character, I could do log_entry[:-1]. I use this trick constantly when cleaning up trailing whitespace or commas from a data import.

Skipping characters with the step value

Finally, there's a third optional value in the slice: the step. It looks like [start:stop:step]. You won't use this every day, but it's incredibly powerful. For instance, if I had a string of IDs and I only wanted every second character for some reason:

id_string = "A1B2C3D4"
every_other = id_string[::2]
print(every_other) # Output: ABCD

A little pro-tip: if you ever see [::-1] in a codebase, don't be confused. That's the Pythonic way to reverse a string. It starts at the end and steps backward by 1 until it hits the beginning.




📋 Practical Task

Exercise: The Product SKU Decoder

You are working on an inventory system where product SKUs are formatted as a single string: "CAT-12345-BLUE". The format is always:

  • First 3 characters: Category
  • Characters from index 4 to 8: Product ID
  • Everything from index 10 to the end: Color

Write a script that takes the string sku = "CAT-12345-BLUE" and uses slicing to create three separate variables: category, product_id, and color. Print each variable to verify you've captured the text exactly, without including the hyphens.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.