String Slicing
Python · Strings
Theory
Slicing extracts part of a string with s[start:stop:step]. Indexes start at 0, start is included and stop is excluded, so for s = 'TechTown', s[0:4] is 'Tech' (positions 0, 1, 2, 3). Leave start out to begin at the start, leave stop out to go to the end, so s[4:] is 'Town'. Negative indexes count from the end: s[-1] is 'n' and s[-4:] takes the last four characters.
The step picks every n-th character: s[::2] gives 'TcTw', and a negative step walks backwards, so s[::-1] reverses the string. Slicing is forgiving: out-of-range bounds are clipped instead of raising errors, so s[100:] is just '' (while plain indexing s[100] raises IndexError). A slice always creates a new string; the original is unchanged. The exact same syntax works on lists and tuples.
Why we use it
Data often hides useful pieces at fixed positions: the year in '2024-03-15', a prefix code, the last 4 digits of a number. Slicing pulls them out in one short, fast expression without loops.
When to use it
Use slicing for fixed-position extraction, prefixes and suffixes, and quick reversal. When the position depends on content (like 'everything after @'), combine it with .find() or use .split() instead.
How it works
- Evaluate s[0:4]
- Is any bound negative? Yes: Convert it: add len(s) to it. No: Use it as given.
- Clip start and stop into the range 0..len(s)
- Take characters from start up to (not including) stop, moving by step
- Return the new string 'Tech'
Syntax
string[start:stop:step]Example
name = 'TechTown'
print(name[0:4])
print(name[::-1])Key points
- Start is included, stop is excluded: s[0:4] has 4 characters
- Negative indices count from the end of the string
- [::-1] is a common idiom to reverse a string
- Out-of-range slices return '' instead of raising IndexError
- The same slicing works on lists and tuples