Python:
Extracting substrings

How to:

# Using slice notation
text = "Python rocks!"
substring = text[7:12]
print(substring)  # Output: rocks

# Using the slice() function
slice_object = slice(7, 12)
print(text[slice_object])  # Output: rocks

# Using str.split() and accessing the element
parts = text.split()
print(parts[1])  # Output: rocks!

Deep Dive

Historically, the concept of string manipulation, including substring extraction, was crucial in early programming languages such as C, where it was a more complex task involving pointers. With Python, the simplicity is dialed up to eleven - more intuitive and less error-prone.

Python provides multiple alternatives for extracting substrings. While the examples used slice notation which is super direct, methods like split() can be handy when you’re dealing with delimiters or whitespace.

Under the hood, Python strings are arrays of bytes representing Unicode characters. But unlike arrays in other languages, Python strings are immutable, which means you can’t change them after creation. This aspect is essential when understanding why substring operations don’t modify the original string but instead create a new one.

See Also