Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
19: String Indexing and Slicing
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.
There are no comments for now.