API Navigator Logo

Extracting a Substring in Python

Author: Newtum

This example explains how to extract a portion of a string, known as a substring, using Python's string slicing notation.

String Slicing Basics

Python's slicing syntax `[start:stop:step]` is a powerful way to get substrings. The `start` index is inclusive, and the `stop` index is exclusive.

my_string = "Programming with Python"

# Get characters from index 0 up to (but not including) index 11
substring1 = my_string[0:11]
print(f"Substring 1: {substring1}")

# You can omit the start index if it's 0
substring2 = my_string[:11]
print(f"Substring 2: {substring2}")

# You can omit the end index to go to the end of the string
substring3 = my_string[17:]
print(f"Substring 3: {substring3}")

# Get the entire string
substring4 = my_string[:]
print(f"Substring 4: {substring4}")

Negative Indexing

You can use negative indices to slice from the end of the string.

my_string = "Programming with Python"

# Get the last 6 characters
last_six = my_string[-6:]
print(f"Last 6 characters: {last_six}")

# Get all but the last 7 characters
all_but_last_seven = my_string[:-7]
print(f"All but last 7: {all_but_last_seven}")

Slicing with a Step

The optional `step` argument allows you to take every Nth character.

my_string = "0123456789"

# Get every second character
every_second = my_string[::2]
print(f"Every second character: {every_second}")

# Reverse the string with a step of -1
reversed_string = my_string[::-1]
print(f"Reversed string: {reversed_string}")