Lesson guide
What this Python exercise practices
Extract a Substring by Index is a intermediate practice lesson that focuses on strings, formatting, traversal. It is designed to be solved in about 15 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- String values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 15 minutes
Practice path
Summary
Return a substring from a string given start and end indices (inclusive), handling negative and out-of-range indices gracefully.
Problem statement
Implement extract_substring(s, start, end) that returns the substring of s starting at index start and ending at index end (inclusive). Indices are 0-based. Both start and end may be negative (meaning count from the end, like Python indexing). If an index is out of range it should be clamped to the valid bounds of the string. If after clamping start > end, return the empty string. Do not use print; return the substring.
Task
Write a function that extracts a substring from index start to end (inclusive), supporting negative indices and clamping out-of-range values.
Examples
Basic example
Input
extract_substring('hello', 1, 3)
Output
ell
Explanation
Characters at indices 1..3 are 'e','l','l' -> 'ell'.
Input format
A string s and two integers start and end, passed as arguments to extract_substring(s, start, end).
Output format
A string: the substring from start to end inclusive (or empty string if start > end after clamping).
Constraints
- Do not use external libraries. - s length can be 0..1000. - start and end are integers and may be negative or outside string bounds. - Must handle negative indices by counting from the end (like Python negatives).
Samples
Sample input 0
extract_substring('python', -3, -1)
Sample output 0
hon
Explanation 0
Indices -3..-1 correspond to 'h','o','n'.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.