Python Indexing & Slicing Lab

Lab 1: The Timestamp Extractor (Beginner)

Scenario: Standard ISO logs start with a timestamp like 2026-01-29T14:30:05Z. You only need the Year and the Time.

Task: Use slicing to extract the first 4 characters and characters from index 11 to 19.

Python

log_entry = "2026-01-29T14:30:05Z"

# 1. Extract Year (Start to index 4)
year = log_entry[:4]

# 2. Extract Time (From 11 to 19)
time = log_entry[11:19]

print(f"Audit Date: {year}, Audit Time: {time}")

Lab 2: The Extension Auditor (Intermediate)

Scenario: You are writing a security scanner for uploaded files. You need to identify the file extension, regardless of how long the filename is.

Task: Use negative indexing to grab the last 3 characters of a filename.

Python

filename = "system_vulnerability_report_final_v1.pdf"

# Use negative slicing to get the last 3 chars
extension = filename[-3:]

if extension == "pdf":
    print("Document analysis triggered...")
elif extension == "exe":
    print("ALERT: Executable detected!")

Lab 3: The “Sanity Check” (Intermediate)

Scenario: A developer accidentally sent a list of sensitive IPs with a “header” and a “footer” string that shouldn’t be there. data = ["HEADER", "192.168.1.1", "10.0.0.5", "172.16.0.2", "FOOTER"]

Task: Use slicing to remove the first and last elements in a single “Symmetrical Slice”.

Python

data = ["HEADER", "192.168.1.1", "10.0.0.5", "172.16.0.2", "FOOTER"]

# Symmetrical slice to 'trim' the ends
clean_ips = data[1:-1]

print(f"Cleaned IP List: {clean_ips}")

Lab 4: The Dynamic Image Parser (Architect Level)

Scenario: You have a Docker image string: registry.hub.docker.com/library/python:3.10-slim. You need to extract the Tag (everything after the colon) dynamically.

Task: Find the index of the colon and slice the string from that point to the end.

Python

image_path = "ghcr.io/devsecops/web-app:v2.4.1-beta"

# 1. Find the position of the colon
colon_pos = image_path.find(":")

# 2. Slice from colon_pos + 1 to the end
tag = image_path[colon_pos + 1:]

print(f"Deploying Version: {tag}")

Lab 5: The Reversed Audit Log (Pro Level)

Scenario: A buffer stores the last 5 security events, but they are in “Oldest First” order. For your dashboard, you need them in “Newest First” (Reversed).

Task: Use the step parameter to reverse the list.

Python

events = ["Login", "File_Edit", "File_Delete", "Logout", "Admin_Access"]

# The "Pythonic" reversal trick
reversed_events = events[::-1]

print(f"Latest activity first: {reversed_events}")

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top