String Manipulation and File Handling
String Manipulation and File Handling
This note covers essential string operations and file handling techniques in Python that appear frequently in the AQA exam.
---
String Manipulation
A string is a sequence of characters. In Python, strings are immutable (they cannot be changed in place — operations return a new string).
Accessing Characters
Each character has an index starting from 0:
word = "COMPUTER"
# Index: 01234567
print(word[0]) # C
print(word[3]) # P
print(word[-1]) # R (last character)
String Length
word = "Hello"
print(len(word)) # 5
Slicing (Substrings)
Slicing extracts part of a string using [start:stop]. The stop index is not included.
word = "COMPUTER"
print(word[0:3]) # COM
print(word[3:6]) # PUT
print(word[:4]) # COMP (from start)
print(word[4:]) # UTER (to end)
Common String Methods
| Method | Purpose | Example | Result |
|---|---|---|---|
.upper() | Convert to uppercase | "hello".upper() | "HELLO" |
.lower() | Convert to lowercase | "HELLO".lower() | "hello" |
.strip() | Remove leading/trailing whitespace | " hi ".strip() | "hi" |
.find(x) | Find index of substring | "hello".find("ll") | 2 |
.replace(a,b) | Replace occurrences | "cat".replace("c","b") | "bat" |
.count(x) | Count occurrences | "hello".count("l") | 2 |
.split(x) | Split into list | "a,b,c".split(",") | ["a","b","c"] |
Concatenation and Conversion
first = "Bright"
last = "Revision"
full = first + " " + last # "Bright Revision"
age = 16
message = "Age: " + str(age) # Must convert int to str
Traversing a String
word = "Hello"
for char in word:
print(char)
# Or by index:
for i in range(len(word)):
print(word[i])
ASCII Conversion
print(ord("A")) # 65 — character to ASCII code
print(chr(65)) # A — ASCII code to character
---
String Manipulation Exam Examples
Example 1: Extract initials
name = "Alan Turing"
parts = name.split(" ")
initials = parts[0][0] + parts[1][0]
print(initials) # AT
Example 2: Reverse a string
word = "Python"
reversed_word = word[::-1]
print(reversed_word) # nohtyP
Example 3: Check for a palindrome
word = input("Enter a word: ").lower()
if word == word[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
---
File Handling
Programs need to read from and write to files to store data persistently (data that remains after the program closes).
Opening Files
Python uses the open() function with a mode:
| Mode | Purpose | Creates file? |
|---|---|---|
"r" | Read only | No (error if missing) |
"w" | Write (overwrites existing content) | Yes |
"a" | Append (adds to end) | Yes |
Writing to a File
file = open("scores.txt", "w")
file.write("Alice,85\n")
file.write("Bob,92\n")
file.close()
Using with (recommended) — automatically closes the file:
with open("scores.txt", "w") as file:
file.write("Alice,85\n")
file.write("Bob,92\n")
Reading from a File
# Read entire file
with open("scores.txt", "r") as file:
content = file.read()
print(content)
# Read line by line
with open("scores.txt", "r") as file:
for line in file:
print(line.strip())
# Read all lines into a list
with open("scores.txt", "r") as file:
lines = file.readlines()
Appending to a File
with open("scores.txt", "a") as file:
file.write("Charlie,78\n")
Working with CSV-Style Data
# Reading and processing
with open("scores.txt", "r") as file:
for line in file:
parts = line.strip().split(",")
name = parts[0]
score = int(parts[1])
print(f"{name} scored {score}")
Common File Operations
# Count lines in a file
with open("data.txt", "r") as file:
count = 0
for line in file:
count += 1
print(f"The file has {count} lines")
# Search for a record
with open("scores.txt", "r") as file:
for line in file:
if "Alice" in line:
print("Found:", line.strip())
---
Exam Tips
- The
withstatement is preferred — examiners accept both styles butwithshows good practice - Remember that
"w"mode overwrites the entire file — use"a"to add data \ncreates a new line when writing;.strip()removes it when reading- String indexing starts at 0 — this catches many students out
- When tracing string operations, write out the index numbers above each character
- Know the difference between
.read()(whole file as one string),.readline()(one line), and.readlines()(list of all lines)