Track progress, take quizzes and save notes on this lesson.

Free forever · no card needed

Start free
Intermediate

String Manipulation and File Handling

2.2.3 Additional programming techniques

Aligned to the OCR J277 specification

Level
Intermediate
Reading time
6 min
Published
11 June 2026
Updated
1 July 2026
On this page
  1. 1.Strings as Sequences
  2. 2.String Concatenation
  3. 3.String Slicing
  4. 4.String Operations in Practice
  5. 5.File Handling — Why Files?
  6. 6.Opening, Reading, Writing and Closing Files
  7. 7.Common Exam Mistakes

Key takeaways

  • String indices start at 0, so the first character is at index 0 and the last valid index is len(string) - 1.
  • Slicing uses string[start:end] where start is inclusive and end is exclusive, so "PYTHON"[0:3] gives "PYT" not "PYTH".
  • To concatenate a number with a string you must first cast it to a string using str(); concatenating directly causes a TypeError.
  • Opening a file in write mode ("w") deletes all existing content; use append mode ("a") to add data without losing what is already there.
  • Always close a file after use with file.close() to ensure data is flushed to disk and the file is not locked.

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"

Worth saving these ideas?

Turn what you've read into instant revision cards. Free to get started.

Make flashcards

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

Key terms

String
An ordered sequence of characters, each at a numbered index starting at 0.
Index
The numbered position of a character in a string, starting at 0 for the first character.
Concatenation
Joining two or more strings together using the + operator to produce a new, longer string.
Slicing
Extracting a portion of a string using the syntax string[start:end], where start is inclusive and end is exclusive.
len()
A Python function that returns the total number of characters in a string.
Immutable
Describes strings in Python - characters cannot be changed in place; modifying a string means creating a new one.
File handling
The ability for a program to open, read from, write to, and close files stored on disk, allowing data to persist after the program ends.
Open mode
The mode in which a file is opened: "r" for reading, "w" for writing (overwrites), "a" for appending (adds to end).
readline()
A Python file method that reads one line at a time from an open file; returns an empty string when the end of the file is reached.

Frequently asked questions

The end index in Python slicing is exclusive, meaning the character at that position is not included. To get the first 4 characters of "PYTHON" use [0:4], which gives characters at indices 0, 1, 2, 3.

Opening a file in write mode ("w") overwrites all existing content and starts fresh. Append mode ("a") adds new data to the end of the file without deleting what is already there.

You must convert the number to a string first using str(). For example, "Score: " + str(87) works correctly. Writing "Score: " + 87 causes a TypeError because you cannot concatenate a string and an integer directly.

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 min

6 min

Lesson

Arrays and Records

OCR GCSE Computer Science · OCR J277

1 month ago

6 min

9 min

Top students don’t revise more. They revise what counts.

Start revising free

Free to start. No card needed.