String Indexing and Slicing
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)In Python, a string (str) is an immutable sequence of Unicode characters. You can inspect characters and slice substrings, but you cannot alter individual characters in place.
String indexing
Index is the position number of a character in a string. The first character has index 0, and a negative index counts from the end, so -1 is the last character.
Characters in a string are indexed starting from 0. Negative indices count from the end.
lang = "Python"print(lang[0])print(lang[-1])Example 1 · Reading an order id
order_id = "ORD-7581"print(order_id[0])print(order_id[-1])print(len(order_id))O 1 8
What this code does
order_id[0]is the first character andorder_id[-1]is the last one.lencounts 8 characters, so the last valid index is 7.
The console displays P and n. Attempting lang[0] = 'J' raises a TypeError: 'str' object does not support item assignment because strings are immutable.
Substring slicing
Slice is a part of a string taken with s[start:stop]. It includes start and leaves out stop, and it never raises an error for out-of-range numbers.
Extract a substring using string[start:stop:step]. The character at stop is not included.
tag = "#MentorNxt"clean_tag = tag[1:]print(clean_tag)Example 2 · Cutting a product code into parts
sku = "PROD-2026-ENG-42"category = sku[:4]year = sku[5:9]item_id = sku[-2:]
print(f"Category: {category}")print(f"Year: {year}")print(f"ID: {item_id}")Category: PROD Year: 2026 ID: 42
What this code does
- Slices product category (
PROD). - Extracts release year (
2026). - Extracts numeric item id (
42).
tag[1:] extracts everything starting from index 1 to the end, producing 'MentorNxt'.
Reversing strings with [::-1]
Step is the third number in s[start:stop:step]. It says how far to move each time, and a step of -1 walks backwards through the string.
Step backwards with a step of -1 to reverse any string in a single operation.
word = "radar"is_palindrome = word == word[::-1]print(f"Is palindrome: {is_palindrome}")Example 3 · Every second digit of an account number
account = "8812093456"print(account[::2])print(account[-4:])print("*" * 6 + account[-4:])81035 3456 ******3456
What this code does
[::2]starts at the beginning and takes every second character.[-4:]keeps the last four characters.- Repeating
"*"six times and adding them hides the start of the number.
Because 'radar' spelled backwards equals 'radar', is_palindrome evaluates to True.
Next step
Check your understanding
9 quick questions