Explain Codes LogoExplain Codes Logo

How do I get a substring of a string in Python?

python
substring
slicing
string-manipulation
Anton ShumikhinbyAnton Shumikhin·Nov 8, 2024
TLDR

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):

# Who doesn't love a good slice? substring = text[2:6]

Bravely leave start or end to their own devices to slice from the start or up to the end, respectively (they've got this):

substring = text[:6] # Substring? More like sub-starting! substring = text[2:] # To the end and beyond!

Negative indices? No problem—they count from the end, not unlike brave explorers returning home. text[-4:] scoops up the last four characters:

# "I'll take the last four characters, please." substring = text[-4:]

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:

substring = text[:-1] # "I never liked the end anyway." whole_string_copy = text[:] # "One whole string to go, please!"

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:

is_identical = x == x[:] # "Mirror, mirror on the wall..."

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:

reversed_string = text[::-1] # "Whoa, I think that string just did a 180!" alternate_characters = text[::2] # "Every other character, step forward!"

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.

substring = text[start:start + LENGTH] # For when size matters

Variables as indices? Why not!

Fancy dynamic substring extraction? Use variables as slice boundaries:

a, b = 2, 6 # "Meet start and end. They're variable." substring = text[a:b] # Slicing dynamics in action!

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:

trim_last_two = text[:-2] # "The last two? Not a fan." penultimate_character = text[-2] # "The one before the last one? My favorite!"

And, you can even do some backward extraction:

substring = text[-3:-1] # "Just popping to the end for a sec!"

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:

substring = text[2:100] # "Even if you overshoot, I've got you covered."

Efficient substring creation: Pro move

Slicing provides efficient substring creation and is highly favored by Python's optimized internals:

prefix_removed = text[1:] # "First one out!" suffix_removed = text[:-1] # "And there goes the last one!"