How do I get a substring of a string in Python?
To extract a substring in Python, we deploy slicing as our trusty tool: string[start:end]
. With text[2:6]
, we've cleverly claimed characters 3 to 6 (and don't forget, indexing has a soft spot for 0):
Bravely leave start
or end
to their own devices to slice from the start or up to the end, respectively (they've got this):
Negative indices? No problem—they count from the end, not unlike brave explorers returning home. text[-4:]
scoops up the last four characters:
Slicing tips, tricks and pizzazz
Selective omission and copying strings
Want to omit certain characters like a master or copy an entire string like a pro? Use these nifty patterns:
With these techniques under your belt, you can trim prefixes or suffixes and even check for string equality with its slice copy—like checking if your haircut is symmetrical:
Shake it up: Reverse and skip
Want to stir things up a bit? Try reversing a string or selecting every nth character (e.g., alternate characters). It’s like a party trick, but with code:
Precision slicing: Defining length
And for those who prefer precision, replicate the behavior of substring functions from other languages that use a start position and length.
Variables as indices? Why not!
Fancy dynamic substring extraction? Use variables as slice boundaries:
Negative slicing: The end is just the beginning
Who said starting from the end isn't fashionable? Negative slicing lets you work with substrings relative to the end of the string:
And, you can even do some backward extraction:
Code with grace: Out-of-bound indices
Python slicing is all about grace under pressures like out-of-bounds indices; it doesn't break a sweat:
Efficient substring creation: Pro move
Slicing provides efficient substring creation and is highly favored by Python's optimized internals:
Was this article helpful?