3.2.8 - String operations and conversions (Python)
String operations select and combine text, while conversions connect text with numeric processing. You will use Python indexes, slices, character codes and conversions without confusing their roles.
Length and character position
A string is a sequence of characters with a length and indexed positions.
word = "PLANET"
print(len(word))
print(word[0])
print(word.find("N"))
The outputs are 6, P and 3. len() counts characters; square brackets obtain the character at the stated zero-based index; .find() finds the first occurrence's index. The indexes for PLANET are 0:P, 1:L, 2:A, 3:N, 4:E, 5:T. The final valid index is length minus one. Python .find() returns -1 if the text is absent; direct indexing outside the valid range causes an error. Distinguish searching for a character's position from obtaining the character at a known position.
Substrings and concatenation
A substring extracts part of a string, while concatenation joins strings into a new string.
Python's slice text[start:stop] includes the start index and excludes the stop index. For PLANET, [1:4] selects indexes 1, 2, 3 to produce LAN. AQA supplied SUBSTRING(1,3,word) includes the final index and therefore selects the same characters. Translate the endpoint rather than copying it unchanged.
word = "PLANET"
label = "Route " + word[1:4]
print(label)
The result is Route LAN. + joins the characters of its two string operands in order; it does not add a space automatically. The space belongs in "Route ". Strings are immutable: a slice produces a new string rather than changing the original. Store a new value if it is needed later.
Selecting a label substring
{"code":"word = "PLANET"\nlabel = "Route " + word[1:4]\nprint(label)","instructions":"Predict and run. Change the slice from [1:4] to [1:5], run again and explain the extra character using its index."}
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account