String Indexing & Slicing

Difficulty: Beginner

Every character in a Python string has a position called an index. Indexing starts at 0, so the first character is at index 0, the second at index 1, and so on. You access a single character using square brackets: text[0] returns the first character.

Python also supports negative indexing, which counts from the end of the string. Index -1 is the last character, -2 is the second to last, and so on. This is extremely convenient when you need characters relative to the end without knowing the string's length.

Slicing extracts a substring using the syntax string[start:stop:step]. The start index is inclusive and the stop index is exclusive. If you omit start, it defaults to 0; if you omit stop, it defaults to the length of the string. The optional step controls the stride between characters.

A common interview trick is reversing a string with slicing: text[::-1]. The -1 step walks backward through the entire string. Understanding slicing thoroughly is critical because the same syntax applies to lists, tuples, and other sequence types in Python.

Code examples

Basic Indexing and Negative Indexing

text = "Python"

print(text[0])
print(text[3])
print(text[-1])
print(text[-3])

text[0] is 'P' (first character), text[3] is 'h', text[-1] is 'n' (last character), and text[-3] is 'h' (third from end).

Slicing with start:stop

text = "Hello, World!"

print(text[0:5])
print(text[7:12])
print(text[:5])
print(text[7:])

text[0:5] extracts indices 0-4. Omitting start defaults to 0; omitting stop goes to the end.

Slicing with Step and Reversal

text = "abcdefghij"

print(text[::2])
print(text[1::2])
print(text[::-1])
print(text[7:2:-1])

Step 2 takes every second character. Step -1 reverses the string. text[7:2:-1] walks backward from index 7 to index 3 (stop is exclusive).

Key points

Concepts covered

indexing, negative indexing, slicing, step, string reversal