StudyVault
Home Unit Overview Exam Technique Revision Techniques ← Previous Lesson Next Lesson →

← Back to Dashboard

Overlay:
0:00 / 0:00 Narration generated using AI text-to-speech.

String Manipulation and Random Numbers

Programs spend a great deal of their time handling text. A login screen checks how long a password is, a school system builds a username from a name, a game turns letters into numbers to scramble a message. All of that is string manipulation. Add one more tool — a way of producing an unpredictable number — and you can also write dice games, shuffled quizzes and simulations.

When a question asks you to write or refine a program, you may answer in the exam reference language or in a high-level language you know, such as Python. The choice is yours. Every code block in this lesson is written in the exam reference language, except one clearly labelled Python comparison near the end.

Length, and counting from zero

A string is a sequence of characters. Each character sits at a numbered position called an index, and indexes start at 0, so the first character is at index 0 and the last is at index length minus one. To find how many characters a string holds, write the variable name followed by .length. There are no brackets after it.

word = "Programming"
print(word.length)   // displays 11
Key Fact

.length counts characters starting at one, but indexes start at zero. For "Programming" the length is 11 while the last character sits at index 10. Mixing the two up is the single most common slip in string questions.

Substrings: taking part of a string

A substring is a slice of a string. The main operation is .substring(x, i), where x is the starting index and i is how many characters to take, not where to stop. Two shortcuts save you the arithmetic at the ends of a string: .left(i) takes the first i characters and .right(i) takes the last i.

word = "Programming"
print(word.substring(0,7))   // displays Program
print(word.substring(3,4))   // displays gram
print(word.left(3))          // displays Pro
print(word.right(4))         // displays ming

Write the string out with its indexes underneath before you answer. For "Programming":

P  r  o  g  r  a  m  m  i  n  g
0  1  2  3  4  5  6  7  8  9  10

word.substring(3,4) starts at index 3, which holds g, and takes four characters: indexes 3, 4, 5 and 6. Those are g, r, a and m, so the answer is gram.

The trap is reading the 4 as ‘stop at index 4’, which would wrongly give gr. The second number is a count, so the last index used is always x + i - 1 — here 3 + 4 − 1, which is 6.

Changing case

Two more operations return a copy of a string with its letters changed: .upper gives every letter as a capital and .lower gives every letter in small letters. Like .length, neither takes brackets, and neither alters the original variable — you must store or print the result.

word = "Programming"
print(word.upper)   // displays PROGRAMMING
print(word.lower)   // displays programming

The everyday use is comparing input fairly. A user who types YES, Yes or yes means the same thing, so convert before you compare and you only need to test one version.

answer = input("Play again? ")
reply = answer.lower
if reply == "yes" then
    print("Starting a new game")
endif

Concatenation

Concatenation joins strings together with +. The same symbol adds numbers, so watch which one you have: with two strings it sticks them together, and nothing is inserted between them unless you add it yourself.

firstName = "Priya"
surname = "Sharma"
print(firstName + " " + surname)   // displays Priya Sharma

A school builds each username from the first letter of the forename and the whole surname, all in small letters. That needs three of the operations above: take a substring, change the case, then concatenate.

firstName = input("Forename: ")
surname = input("Surname: ")
initial = firstName.left(1)
username = initial.lower + surname.lower
print(username)

Given ‘Priya’ and ‘Sharma’, initial holds P, initial.lower gives p, surname.lower gives sharma, and the two join to make psharma.

Character codes: ASC and CHR

Inside the computer every character is stored as a number from a character set such as ASCII. Two operations move between the two forms. ASC(...) takes a character and returns its code as a number. CHR(...) takes a code and returns the character. They are exact opposites of one another.

print(ASC('A'))   // displays 65
print(CHR(97))    // displays a

Because the codes for the letters run in order, arithmetic on a code shifts a letter along the alphabet. That is the whole idea behind a simple substitution cipher.

letter = 'a'
code = ASC(letter)
shifted = CHR(code + 1)
print(shifted)    // displays b

Random numbers

Random number generation is what makes a program unpredictable. The operation is random(min, max), and it returns a value between the two arguments inclusive — both ends can come up. Give it two whole numbers and you get a whole number back; give it two decimals and you get a decimal back.

diceRoll = random(1,6)
print(diceRoll)              // a whole number from 1 to 6

temperature = random(-1.0,10.0)
print(temperature)           // a decimal from -1.0 to 10.0
Key Fact

random(min, max) includes both end values, so a six-sided dice is random(1,6). Writing random(1,7) or random(0,6) gives seven possible outcomes instead of six, which quietly breaks the game rather than causing an error message.

A quiz holds its questions in an array and picks one at random. The array has five elements at indexes 0 to 4, so the range passed to random must be 0 to 4 — not 1 to 5, and not 0 to 5.

array questions[5]
questions[0] = "What is a variable?"
questions[1] = "What is a constant?"
questions[2] = "What is an array?"
questions[3] = "What is a record?"
questions[4] = "What is a function?"

pick = random(0,4)
print(questions[pick])

Because the array is indexed from 0, the top argument is always the number of elements minus one. Get that wrong and the program either never asks the last question or crashes when it looks past the end of the array.

If you choose to answer in a high-level language, Python does the same jobs with different names. The code below is Python, not the exam reference language.

import random

word = "Programming"
print(len(word))          # 11
print(word[3:7])          # gram
print(word.upper())       # PROGRAMMING
print(ord('A'))           # 65
print(chr(97))            # a
print(random.randint(1,6))

Watch the one real difference in meaning. Python’s slice word[3:7] runs from index 3 up to but not including index 7, while word.substring(3,4) starts at index 3 and takes four characters. Both give gram here, but the second number means something different in each language, so never carry one habit into the other.

How these appear in exam questions

  • Short ‘state the output’ questions give you a string and one operation. Write the string out with its indexes underneath and count on your fingers — guessing costs marks that careful counting does not.
  • Trace questions run three or four lines and ask what is displayed. Track every variable after every line, not just the last one.
  • Writing questions ask for one or two lines of code. Answers in natural English or bullet points earn nothing here, so always write real code.
  • Random number questions nearly always test the inclusive range. Read the scenario for the smallest and largest values wanted, then map them straight onto the two arguments.
Key Fact

Seven operations cover this whole topic: .length, .substring(x, i) with .left(i) and .right(i), .upper, .lower, + for joining, ASC(...) and CHR(...) for character codes, and random(min, max). Learn the exact spelling of each one.

Practice Questions

Test yourself on this lesson. Pick a question, write your answer, then get it marked.

AI feedback
AI feedback is guidance, not a final exam mark. If you disagree, your teacher's view is always the tie-breaker.
← Back to unit
Video

© 2026 StudyVault · About · FAQ · Copyright & IP · Privacy · Disclaimers

StudyVault Education Ltd · registered in England and Wales, company no. 17490559 · 71–75 Shelton Street, London WC2H 9JQ