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`.

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]?

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)