Intermediate

String Manipulation and File Handling

AicademyAicademy
·OCR GCSE Computer Science·OCR J277·6 min
2.2.3 Additional programming techniques

Strings as Sequences

A string is an ordered sequence of characters. Each character occupies a numbered position called an index, starting at 0 for the first character.

word = "PYTHON"
#        0 1 2 3 4 5
Index012345
CharacterPYTHON

Accessing a single character by index:

word[0]   # 'P'
word[3]   # 'H'
word[-1]  # 'N'  (negative index counts from the end)

The length of a string is the total number of characters. len("PYTHON") returns 6. The valid indices run from 0 to len(string) - 1.

Strings are immutable in Python — you cannot change a character in place. Modifying a string means creating a new one.

String Concatenation

Concatenation joins two or more strings together to form a new, longer string. Use the + operator.

first = "Alan"
last = "Turing"
full = first + " " + last    # "Alan Turing"

Worked example — build a personalised message:

name = input("Enter your name: ")
score = int(input("Enter your score: "))
message = "Well done, " + name + "! You scored " + str(score) + " points."
print(message)

Note: score is an integer, so it must be cast to a string with str(score) before it can be concatenated. Concatenating a string and an integer directly causes a TypeError.

String repetition (* with a number) repeats a string:

line = "-" * 20    # "--------------------"

Concatenation always produces a new string. The original strings are unchanged.

OperationExampleResult
Concatenation"cat" + "nap""catnap"
Concatenation with space"Alan" + " " + "Turing""Alan Turing"
Repetition"ha" * 3"hahaha"

String Slicing

Slicing extracts a portion of a string — a substring — without modifying the original. The syntax is string[start:end], where start is inclusive and end is exclusive.

text = "COMPUTER"
#       01234567

text[0:4]    # "COMP"  — characters at indices 0, 1, 2, 3
text[4:8]    # "UTER"  — characters at indices 4, 5, 6, 7
text[2:5]    # "MPU"   — characters at indices 2, 3, 4

Omitting start or end uses the beginning or end of the string as the default:

text[:4]     # "COMP"  — from the start up to (not including) index 4
text[4:]     # "UTER"  — from index 4 to the end
text[:]      # "COMPUTER" — full copy

Worked example — extract the area code from a phone number:

phone = "01234567890"
area_code = phone[:5]    # "01234"
subscriber = phone[5:]   # "567890"

Worked example — check file extension:

filename = "report.pdf"
extension = filename[-3:]   # "pdf"

When slicing, string[start:end] — the character at end is not included. "PYTHON"[0:3] gives "PYT", not "PYTH".

String Operations in Practice

Combining concatenation and slicing enables many common text-processing tasks.

Worked example — format a student's initials from their full name:

first = "Mohammed"
last = "Ali"
initials = first[0] + ". " + last[0] + "."    # "M. A."

Worked example — capitalise a name and check its length:

name = input("Enter name: ")
upper_name = name.upper()               # "alice" → "ALICE"
print(upper_name, "has", len(name), "characters")

(Extra context — .upper(), .lower(), .find(), and other string methods are useful in practice. Only concatenation and slicing are explicitly required by OCR J277 2.2.3, but string methods may appear in code you are asked to read and trace.)

Worked example — build a formatted output line:

subject = "Computer Science"
score = 87
grade = "A"
report = subject + ": " + str(score) + "% — Grade " + grade
print(report)   # "Computer Science: 87% — Grade A"

Studying this for an exam?

Generate a personalised learning path for this subject. Free to get started.

Create a learning path

File Handling — Why Files?

Variables store data only while a program is running. When the program ends, variables are lost. Files provide persistent storage — data saved to a file survives after the program closes.

Four core file operations are required by OCR J277:

OperationWhat it does
OpenCreates a connection between the program and the file on disk
ReadReads data from the file into the program
WriteWrites data from the program to the file
CloseBreaks the connection and ensures all data is flushed to disk

Always close a file when you have finished with it. Leaving a file open can cause data loss or lock the file against other programs.

Files are opened in different modes: read mode ("r"), write mode ("w"), and append mode ("a"). Write mode overwrites the existing file content; append mode adds to the end.

Opening, Reading, Writing and Closing Files

Writing to a file:

file = open("scores.txt", "w")    # open for writing
file.write("Alice: 95\n")
file.write("Bob: 78\n")
file.close()                       # always close when done

Reading from a file:

file = open("scores.txt", "r")    # open for reading
line = file.readline()            # reads one line at a time
while line != "":
    print(line)
    line = file.readline()
file.close()

Worked example — save a user's high score, then read it back:

# Save
file = open("highscore.txt", "w")
file.write(str(high_score))
file.close()

# Load
file = open("highscore.txt", "r")
saved_score = int(file.readline())
file.close()
print("Previous best:", saved_score)

Note: file.write() expects a string — cast numeric values with str() before writing.

Common Exam Mistakes

1. Forgetting that slice end is exclusive

"PYTHON"[0:3] gives "PYT" — the character at index 3 ("H") is not included. To get the first four characters use [0:4], not [0:3].

2. Not casting when concatenating strings and numbers

"Score: " + 87 causes a TypeError. Always convert numbers to strings before concatenation: "Score: " + str(87).

3. Not closing files after use

Failing to call file.close() may leave data unwritten (buffered in memory rather than flushed to disk) and can prevent other parts of the program from accessing the file.

4. Confusing write mode and append mode

Opening a file in "w" mode deletes all existing content and starts fresh. To add data without losing what is already there, use "a" (append) mode.

MistakeCorrection
"PYTHON"[1:4] expecting "PYT""PYTHON"[1:4] gives "YTH"; use [0:3] for "PYT"
"Total: " + total"Total: " + str(total)
Opening with "w" to add recordsUse "a" (append) to preserve existing data

Generate revision on any topic you study

Type any topic you're studying and Aicademy generates a complete lesson, quiz, and flashcard set — personalised to your level.

Lessons on anything

Structured, level-matched lessons on any topic you study

Practice quizzes

Find out what you actually know before the exam does

Flashcard sets

Lock in key concepts with instant revision cards

Ask Aica

Stuck on something? Get a clear explanation, any time

Prev

Data Types and Casting

Next

Arrays and Records

Related lessons

7 Slides

Lesson

Data Types and Casting

OCR GCSE Computer Science · OCR J277

4 days ago

7 Slides

Lesson

Arrays and Records

OCR GCSE Computer Science · OCR J277

4 days ago

7 Slides

Lesson

Programming Fundamentals

OCR GCSE Computer Science · OCR J277

4 days ago

6 Slides

Lesson

Data Representation

OCR GCSE Computer Science · OCR J277

3 days ago