Python String Methods Lab

Lab: The Log Scrubber

Try this in your Python terminal to see the power of chaining:

# Raw, messy log entry from a server
raw_log = "  ERROR: Connection failed from IP 192.168.1.1  \n"

# 1. Clean whitespace
clean_log = raw_log.strip()

# 2. Check if it's an error
is_error = clean_log.startswith("ERROR")

# 3. Extract the IP (The Architect way)
log_parts = clean_log.split(" ")
ip_address = log_parts[-1]

print(f"Status: {is_error}, IP: {ip_address}")

Lab 1: The Config File Sanitizer (Beginner)

Scenario: You have a configuration file where users often add accidental spaces or use inconsistent casing. You need to “normalize” these keys to ensure your script reads them correctly.

Task: Clean the following list of raw configuration keys so they are all lowercase, have no leading/trailing spaces, and replace internal spaces with underscores.

raw_configs = ["  Max_Connections  ", "timeout ", "  RETRY_COUNT", "Buffer Size  "]

# Your Code Here:
for config in raw_configs:
    # 1. Strip spaces
    # 2. Convert to lowercase
    # 3. Replace spaces with underscores
    clean_config = config.strip().lower().replace(" ", "_")
    print(f"Validated: '{clean_config}'")

Lab 2: The Secret Masker (Intermediate)

Scenario: For security reasons, you must never print a full API Key in your logs. You need to write a script that “masks” a key, showing only the first 4 and last 4 characters, with asterisks in the middle.

Task: Take an API key string and return the masked version.

api_key = "prod_9283746551029384756"

# Logic:
# 1. Get the first 4 chars
# 2. Get the last 4 chars
# 3. Use .count() to see how many chars to mask (optional) or use string slicing
# 4. Join them with "********"

prefix = api_key[:4]
suffix = api_key[-4:]
masked_key = prefix + "*" * 10 + suffix

print(f"Logging Access for Key: {masked_key}")

Lab 3: The Automated SQLi Filter (Architect Level)

Scenario: You are building a basic security middleware. You need to detect if a user input string contains common SQL Injection keywords or suspicious characters.

Task: Create a function that checks if a string is “safe.” A string is unsafe if it contains symbols like ', ;, or -- or keywords like DROP or DELETE.

def is_input_safe(user_input):
    # Normalize input for checking
    check_val = user_input.upper()
    
    # Check for keywords
    if "DROP" in check_val or "DELETE" in check_val:
        return False
    
    # Check for suspicious symbols
    if ";" in user_input or "--" in user_input:
        return False
        
    return True

# Test cases
print(is_input_safe("admin' --"))      # Should be False
print(is_input_safe("john_doe_2026"))  # Should be True

Lab 4: CSV Data Extractor (Architect Level)

Scenario: You receive a comma-separated string representing a user’s permissions: Username,Role,Region,Department. You need to extract the Role and Department to verify access.

Task: Use .split() and indexing to extract specific data.

access_log = "amit_sharma,Security_Admin,Mumbai,Infrastructure"

# 1. Split by comma
data = access_log.split(",")

# 2. Assign variables via indexing
username = data[0]
role = data[1]
dept = data[-1]

print(f"User {username} from {dept} is requesting {role} access.")

Lab 5: The File Extension Auditor

Scenario: You are scanning a directory for malware. You only want to analyze files that end in .sh, .py, or .exe.

Task: Write a loop that filters a list of filenames based on their extension.

files = ["backup.zip", "install.sh", "script.py", "virus.exe", "notes.txt"]
dangerous_files = []

for file in files:
    if file.endswith((".sh", ".py", ".exe")):
        dangerous_files.append(file)

print(f"Files to audit: {dangerous_files}")

Challenge Lab: The “Clean URL” Generator

Combine multiple methods to turn a blog title into a URL slug.

  • Input: "How to Secure your Docker Containers in 2026!"
  • Output: "how-to-secure-your-docker-containers-in-2026"

Hint: Use .lower(), .strip(), .replace(), and remember to remove the “!” punctuation!

Leave a Comment

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

Scroll to Top