6.3.3 – String positions and substrings
Treat text as a sequence with precise positions. Measure strings, extract substrings, build new strings and handle empty or boundary cases before accessing characters.
Length and position
A string is an ordered sequence of characters. Letters, digits, spaces and punctuation all occupy positions. Python indexes from zero; len() returns the number of characters, not the final index.
word = "ALGORITHM"
print(len(word))
print(word[0])
print(word[len(word) - 1])
9
A
M
| Character | A | L | G | O | R | I | T | H | M |
|---|---|---|---|---|---|---|---|---|---|
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
For a nonempty string of length n, valid non-negative indexes are 0 through n−1. Selecting word[len(word)] goes one position too far and raises IndexError. A character is represented by a length-one string, so selecting one item still produces Python str.
Spaces count. The string "P2 READY" has eight characters; R is at index 3 because the space at index 2 occupies a position. An empty string has length zero and no valid single-character index.
Substrings and concatenation
A substring is a contiguous part of a string. A slice selects one using start and stop positions. Start is included; stop is excluded. Omitting start means the beginning; omitting stop means the end.
route = "GCSE-CS-26"
level = route[0:4]
subject = route[5:7]
year = route[8:]
label = subject + "-" + level + "-" + year
print(label)
CS-GCSE-26
The level uses indexes 0–3, subject uses 5–6 and year uses 8–9. Concatenation joins strings in the given order. It does not invent separators: the hyphens appear only because the code includes them. Numeric values must be converted to text before concatenating with +; formatting offers another approach in the next lesson.
count = 12
message = "Items: " + str(count)
print(message)
For in-range ordered bounds, a slice's length is stop−start. That reasoning does not extend unchanged to bounds beyond the string; Python clips a slice to the available characters.
Slices and safe boundary handling
Single-item indexing and slicing behave differently at a boundary. A missing single position is an error, but a slice can be empty or stop at the end without an error.
text = "CODE"
print(text[1:3])
print(text[2:20])
print(len(text[3:3]))
print(len(text[4:]))
OD
DE
0
0
The last two slices are empty strings. This is different from text[4], which asks for a nonexistent single character. Python also allows negative indexes: -1 is the final character of a nonempty string. A negative index still fails if the string is empty.
Before selecting the first or final character of an arbitrary input, check its length:
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account