This guide explains String Slicing: Start, Stop, and Step through a focused example and practical reasoning. No prior knowledge of this specific operation is required.
Understanding the Concept
A string slice text[start:stop:step] returns a new substring; stop is excluded. Omitted bounds use appropriate defaults, and a negative step can traverse backward.
When You Would Use This
Extract the prefix, suffix and reverse of an order code.
Step-by-Step Example
order_code = "INV-2026"
print(order_code[:3])
print(order_code[4:])
print(order_code[::-1])
How the Example Works
The first slice is INV, the second is 2026, and the final slice reverses every code point. Slices tolerate many out-of-range bounds without an IndexError.
Example Output
INV
2026
6202-VNI
Try It Yourself
Extract only the final four characters of "REF-1048".
Common Beginner Mistakes
- Assuming the stop index is included.
- Confusing
text[4]withtext[4:]. - Expecting reversed code-point order to preserve complex grapheme clusters.
Key Takeaways
- A string slice
text[start:stop:step]returns a new substring;stopis excluded. - The first slice is
INV, the second is2026, and the final slice reverses every code point. - Avoid this mistake: Assuming the stop index is included.