Slicing Strings
Slicing reads a portion of a sequence using start, stop, and an optional step. The stop position is excluded, which lets adjacent slices fit together cleanly.
Understand the idea
Missing boundaries mean the beginning or end. Negative positions count back from the end, and a negative step can reverse traversal. Ordinary string slicing clamps boundaries outside the sequence, unlike indexing one missing position, which raises IndexError. Keep slices readable when the positions have domain meaning.
Where to try it
Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.
A worked example
code = "BH-2048"
print(code[:2])
print(code[3:])
print(code[-4:])
Read the result
The results are BH, 2048, and 2048. The hyphen sits at index 2 and is excluded from the final two slices.
Try one change
Split a labelled code into its prefix and numeric text, then decide whether split('-', 1) communicates the structure better.