Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Extract a Substring by Index

Return a substring from a string given start and end indices (inclusive), handling negative and out-of-range indices gracefully.

Python practice15 minVariables & Data TypesIntermediateLast updated January 3, 2026

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

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 1

Input

extract_substring('python', -3, -1)

Output

hon

Indices -3..-1 correspond to 'h','o','n'.