Topic 17 of 58
String Slicing
Overview
Slicing is a powerful syntax feature that extracts a sub-section (substring) from a string. Using the colon notation [start:stop:step], you can effortlessly chop, skip, or reverse sequences. Understanding that the start index is inclusive while the stop index is exclusive is essential for precise data extraction.
Syntax
python
text = "Hello World"
# Basic slicing [start:stop]
print(text[0:5]) # 'Hello' (Indices 0, 1, 2, 3, 4)
print(text[6:11]) # 'World'
# Omitting boundaries assumes the beginning or end
print(text[:5]) # 'Hello' (Starts from 0)
print(text[6:]) # 'World' (Goes to the end)
# Step parameter [start:stop:step]
print(text[::2]) # 'HloWrd' (Skips every other character)
# Reversing a string in one line
print(text[::-1]) # 'dlroW olleH'Common Pitfalls
- Forgetting that the
stopindex is exclusive. Slicing[0:3]returns exactly 3 characters (indices 0, 1, 2). - Unlike direct indexing, slicing does NOT throw an IndexError if you exceed the string's bounds.
text[0:999]will safely return the entire string.
Interview Questions
Q:
What is the most Pythonic way to check if a string is a palindrome (reads the same forwards and backwards)?
A:
By comparing the string to its reversed slice: if text == text[::-1]:.
Real-World Example
Extracting specific structured data from standard identifiers.
example
python
transaction_id = "TXN-2023-88492"
prefix = transaction_id[:3] # 'TXN'
year = transaction_id[4:8] # '2023'
user_id = transaction_id[-5:] # '88492'Check Your Knowledge
Test your understanding of String Slicing with these quick questions.