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).
Concatenation
Joining strings together is usually done with the + operator.
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.
# 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.
(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)
import random
letters = surname[0:3]
randNum = random.randint(1, 99)
# Must cast the integer back to a string to concatenate!
playerID = letters + str(randNum)
print(playerID)
Mark 1 uses exactly [0:3] to slice the 1st, 2nd, and 3rd letters.
Mark 2 generates a valid random int between 1 and 99.
Mark 3 successfully casts the random int to a string.
Mark 4 successfully explicitly concatenates using +.