Extract a substring in Python
Use string slices for index ranges, handle delimiters safely, and account for negative indexes, zero-length requests, and Unicode boundaries.
Use text[start:end]. The starting index is included and the ending index is excluded. Indexes start at zero; omitting either boundary uses the corresponding end of the string.
text = "Hello, world!"
print(text[7:12]) # world
print(text[:5]) # Hello
print(text[7:]) # world!
print(text[-6:-1]) # world
Add a step
text = "abcdefg"
print(text[::2]) # aceg
print(text[::-1]) # gfedcba
The third slice component is the step. It cannot be zero. A negative step traverses in reverse and changes the default start and end boundaries accordingly.
Bounds and immutability
Out-of-range slice boundaries are clipped: text[:100] returns the available text. An individual out-of-range index still raises IndexError. Slicing does not modify the original string; strings are immutable. An implementation may reuse an existing string object for a full slice, so do not rely on getting a distinct identity.
| Task | Expression |
|---|---|
| First N code points, with N nonnegative | text[:n] |
| Last N code points, with N positive | text[-n:] |
| Remove the first and last code point | text[1:-1] |
| Reverse code-point order | text[::-1] |
For n == 0, the last-N result should usually be ""; text[-0:] instead returns the whole string. Unicode code-point boundaries also need not match visible characters, such as a letter followed by a combining accent.
FAQ
How do I take everything before a delimiter? text.partition(",")[0] returns the prefix, or the complete string when no comma exists. text.split(",", 1)[0] is another option. If you use find(), check its result before slicing:
text = "no comma here"
position = text.find(",")
prefix = text[:position] if position != -1 else text
Blindly using text[:text.find(",")] drops the last character when the delimiter is absent because find() returns -1.
Should I choose slicing or split for speed? Choose by the operation: indexes call for slices; delimiters call for string-search or split methods. Benchmark a representative workload only when that code is a measured bottleneck.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan