String Manipulation

Almost every login system and username generator requires string manipulation and randomisation. Learn how to glue strings together (Concatenation) or cut them up (Slicing).

Complex string methods (like regex) are NOT required for J277.

Concatenation

Joining strings together is usually done with the + operator.

# Setting variables
firstName = "Alan"
surname = "Turing"

# Concatenation (Don't forget the space!)
fullName = firstName + " " + surname

Output: "Alan Turing"

Random Numbers

Almost all languages use a library/module to generate random numbers. You must emulate a dice roll or ID generator.

import random

# Generate a random integer between 1 and 6
diceRoll = random.randint(1, 6)

Output: Will randomly be 1, 2, 3, 4, 5, or 6.

Examiner's Eye - The Blank Space Trap

When concatenating two variables together, computers do not automatically add a space. If you write `firstName + surname`, the output will be "AlanTuring". You must explicitly add a space string: `firstName + " " + surname`.

Random Number Masterclass

Master the theory of randomness, the difference between Python and ERL, and walk through a common exam coin-toss simulation.

Paper 2 Prep Python vs ERL

Learn how to generate random numbers using the OCR Exam Reference Language (ERL) and Python's randint(). Includes a step-by-step walkthrough of simulating a coin toss.

The String Slicer (Substrings)

Extracting a substring means taking a precise chunk out of a string based on its Index positions. Remember: Strings always start at Index 0.

Pseudocode Slicing Command:
word[ : ]
Output String: COMP

(Note: Slicing extracts UP TO but NOT INCLUDING the end index.)

Check Your Understanding

1. What does the term "Concatenation" mean?

2. The string is planet = "EARTH". What character is at planet[0]?

3. Which of the following is the correct Python syntax for a random number between 1 and 10?

Written Exam Scenario (AO2/AO3)

Stretch (Grade 9)

"Write an algorithm or line of pseudocode that generates a random Player ID. It must take the first 3 letters of a variable called surname, and concatenate them with a random number between 1 and 99." (5 marks)