You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
This lesson covers string manipulation techniques as required by OCR J277 Section 2.3. String manipulation is the process of examining, modifying, and extracting parts of strings. OCR requires you to know specific string operations including length, substring, upper/lower case conversion, concatenation, and ASCII conversion.
A string is a sequence of characters. Each character in a string has a position (index), starting from index 0.
word = "COMPUTER"
// Index: 0=C, 1=O, 2=M, 3=P, 4=U, 5=T, 6=E, 7=R
The .length property returns the number of characters in a string.
OCR Pseudocode:
word = "Hello"
print(word.length) // Output: 5
Python:
word = "Hello"
print(len(word)) # Output: 5
Note: the length counts all characters including spaces and punctuation. "Hi there!".length = 9.
The .substring(start, end) method extracts a portion of a string from the start index up to (but not including) the end index.
OCR Pseudocode:
word = "COMPUTER"
print(word.substring(0, 3)) // Output: COM
print(word.substring(3, 6)) // Output: PUT
print(word.substring(4, 8)) // Output: UTER
Python:
word = "COMPUTER"
print(word[0:3]) # Output: COM
print(word[3:6]) # Output: PUT
print(word[4:8]) # Output: UTER
| Example | Start | End | Result | Characters Extracted |
|---|---|---|---|---|
"COMPUTER".substring(0, 3) | 0 | 3 | "COM" | Indices 0, 1, 2 |
"COMPUTER".substring(3, 6) | 3 | 6 | "PUT" | Indices 3, 4, 5 |
"COMPUTER".substring(6, 8) | 6 | 8 | "ER" | Indices 6, 7 |
OCR Exam Tip: The
.substring(start, end)method uses zero-based indexing and the end index is EXCLUSIVE (not included). This is a very common source of errors. For"HELLO".substring(1, 4), you get characters at indices 1, 2, 3 — which is "ELL", not "ELLO".
OCR Pseudocode:
word = "Hello World"
print(word.upper) // Output: HELLO WORLD
print(word.lower) // Output: hello world
Python:
word = "Hello World"
print(word.upper()) # Output: HELLO WORLD
print(word.lower()) # Output: hello world
userInput = input("Enter yes or no: ")
if userInput.lower == "yes" then
print("You chose yes")
endif
user_input = input("Enter yes or no: ")
if user_input.lower() == "yes":
print("You chose yes")
OCR Exam Tip: In OCR pseudocode,
.upperand.lowerdo NOT use brackets. In Python,.upper()and.lower()DO use brackets. Make sure you use the correct syntax for whichever language you are writing in.
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.