Strings, Slicing and String Methods
Strings in Python are sequences of characters. Python offers an expressive slicing syntax that lets you extract any section of text effortlessly.
What is it?
String slicing extracts substrings using index notation: `string[start:stop:step]`. Python also has dozens of built-in string methods.
Why is it used?
Sanitizing user inputs, extracting file extensions, reversing strings, and formatting text reports.
Detailed Explanation
Slicing Syntax: `s[start:stop:step]`
• Indexing is zero-based: `s[0]` is the first character.
• Negative indexing: `s[-1]` is the last character.
• `s[0:4]`: Characters from index 0 up to 3.
• `s[:5]`: First 5 characters.
• `s[5:]`: From index 5 to the end.
• `s[::-1]`: Reverses the string in one step!
Essential Methods:
• `.strip()`: Removes leading and trailing whitespace.
• `.lower()` / `.upper()` / `.title()`.
• `.replace(old, new)`.
• `.split(delim)` / `delim.join(list)`.
Syntax Structure
Syntax Blueprint
sub = text[0:5]
reversed_text = text[::-1]
clean = raw.strip().lower()
Code Example
PYTHON Code
# Processing Filenames and User Input
filename = "klic_python_handbook.pdf"
# Slicing: Extracting extension and name
extension = filename[-3:] # Last 3 chars
file_stem = filename[:-4] # Everything except .pdf
print(f"File stem: {file_stem}")
print(f"Extension: .{extension}")
# String Methods
title_text = file_stem.replace("_", " ").title()
print(f"Title: {title_text}")
# Reversing a string with step -1
word = "racecar"
is_palindrome = word == word[::-1]
print(f"Is '{word}' a palindrome? {is_palindrome}")
Explanation of the Code
• `filename[-3:]` uses negative indexing to grab the last 3 characters.
• `.replace("_", " ").title()` cleans and capitalizes words.
• `word[::-1]` reverses the string for palindrome checking.
Expected Output
File stem: klic_python_handbook
Extension: .pdf
Title: Klic Python Handbook
Is 'racecar' a palindrome? True
Real-World Application
Used across file upload handlers to validate file extensions (e.g. ensuring user uploads `.png` or `.pdf`).
Common Mistakes to Avoid
• Strings in Python are immutable. You cannot do `s[0] = 'H'` (raises `TypeError`). You must construct a new string.
• Off-by-one errors: `s[0:5]` grabs 5 characters (indices 0, 1, 2, 3, 4).
Quick Practice Challenge
Extract the domain name from the email `'ashutosh@igmcomputers.com'` using `.split('@')`.
Key Takeaways
• Slicing syntax: `[start:stop:step]`.
• `[::-1]` reverses any sequence cleanly.
• Python strings are immutable.