Home / GCSE · AQA / Computer Science / Programming

CS8String Handling and Random Numbers

3.2.8 String handling

Strings and their length

A string is a sequence of characters: letters, digits, spaces and symbols.

  • Each character has a position, its index, counting from 0, just like an array.
  • Length is the number of characters, including spaces and punctuation. In pseudo-code: LEN('St Ives') is 7. In Python: len("St Ives").
  • The last character is at index LEN − 1.
  • The empty string, '' (Python ""), has length 0. It is useful as the starting value when you build a new string.
  • In Python:
    city = "St Ives"
    print(len(city))                 # 7
    print(city[0])                   # S
    print(city[len(city) - 1])       # s, the last character
  • len() works on lists too: see Arrays and records.
String
A sequence of characters.
Length
The number of characters in a string, including spaces: LEN in pseudo-code, len() in Python.
Empty string
A string with no characters: '' in pseudo-code, "" in Python. Its length is 0.
3.2.8 String handling

Characters and positions

  • One character: write the index in square brackets. word[0] is the first character.
  • Position of a character: POSITION(word, 'e') in pseudo-code, word.find("e") in Python. It gives the index of the first match.
  • If the character isn't in the string, the result is −1, which can never be a real position.
  • Matching is case-sensitive: "Pinecone".find("p") is −1, because the string has a capital P.
  • Pseudo-code:
    word ← 'Pinecone'
    OUTPUT word[0]                  # P
    OUTPUT POSITION(word, 'e')      # 3, the first e
    OUTPUT POSITION(word, 'z')      # -1, not found
  • Python:
    word = "Pinecone"
    print(word[0])            # P
    print(word.find("e"))     # 3
    print(word.find("z"))     # -1
  • In Python you can read word[2] but you can't change it with word[2] = "x". To change a string, build a new one.

Characters are numbered from 0. POSITION finds the first match.

Exam tipWhen a question gives you a subroutine such as POSITION, use it exactly as shown, with its parameters in the same order. In one AQA paper only 40% of students used a given POSITION subroutine correctly, even though the question showed examples.
POSITION / .find()
Returns the index of the first occurrence of a character in a string, or −1 if it isn't there.
3.2.8 String handling

Substrings and slices

A substring is a run of characters next to each other inside a string. AQA's pseudo-code and Python count the end differently.

  • AQA pseudo-code: SUBSTRING(start, end, s). Both the start and the end positions are included. SUBSTRING(1, 4, 'Pinecone') is 'inec'.
  • Python: a slice s[start:end] stops one before the end number. "Pinecone"[1:4] is "ine".
  • So to turn SUBSTRING(a, b, s) into Python, write s[a:b + 1].
  • Leave out the start to begin at 0: s[:3] is the first three characters. Leave out the end to run to the last character: s[4:].
  • Notice the order: AQA's SUBSTRING puts the string last.
  • Python:
    title = "Pinecone"
    print(title[1:4])     # ine
    print(title[:4])      # Pine
    print(title[4:])      # cone

Same start and end numbers, different results.

Worked exampleFrom town ← 'Leicester', get 'ices' in pseudo-code and in Python.
  1. L0 e1 i2 c3 e4 s5 t6 e7 r8number the characters from 0
  2. 'ices' runs from index 2 to index 5find the first and last characters you want
  3. SUBSTRING(2, 5, town)AQA includes both ends
  4. town[2:6]Python stops one before the end, so add 1
SUBSTRING(2, 5, town) and town[2:6]
Exam tipExaminers report that substring questions often go wrong because students start counting at 1. Write the index under each character before you answer.
Substring
Part of a string made of characters that are next to each other.
SUBSTRING(start, end, s)
AQA's pseudo-code substring: from start to end, both included.
Slice
Python's s[start:end]: from start up to, but not including, end.
3.2.8 String handling

Concatenation

  • Concatenation joins strings end to end with +: 'sun' + 'flower' is 'sunflower'.
  • No space is added. If you want one, concatenate it: first + " " + last.
  • Both sides must be strings. Convert a number first with str(), or Python stops with a TypeError.
    first = "Ada"
    last = "Lovelace"
    full = first + " " + last
    print(full)               # Ada Lovelace
    age = 36
    message = full + " was " + str(age)
    print(message)            # Ada Lovelace was 36
  • A comma is not concatenation. message = full, " was " makes a tuple (a pair of values), not one string.
  • Inside print(), commas are fine: print(full, "was", age) prints the items with a space between each.
  • An f-string is another way to build output: print(f"{full} was {age}"). It converts the number for you.
Exam tipExaminers don't give the mark for msg = reg, " is not valid". When a question says store the message in a variable, join the parts with +.
Concatenation
Joining two strings end to end to make a new string, using +.
3.2.8 String handling

Character codes

Every character has a number, its character code. AQA uses ASCII codes, which Unicode shares.

  • Character to code: CHAR_TO_CODE('a') is 97. In Python: ord("a").
  • Code to character: CODE_TO_CHAR(97) is 'a'. In Python: chr(97).
  • Codes come in groups, in order: 'A' to 'Z' are 65 to 90, 'a' to 'z' are 97 to 122, and '0' to '9' are 48 to 57.
  • So if you know 'A' is 65, then 'D' is 68. Each lower-case letter is 32 more than its capital.
  • Is it a capital letter? ord(ch) >= 65 and ord(ch) <= 90. Don't write a chained comparison such as 65 <= ord(ch) <= 90.
  • Moving along the alphabet: chr(ord("c") + 1) is "d".
  • To wrap round at the end of a group, use MOD (%). This moves each digit on by one, so '9' becomes '0':
    digit = "9"
    newCode = (ord(digit) - 48 + 1) % 10 + 48
    print(chr(newCode))       # 0
  • Changing case:
    letter = "g"
    code = ord(letter)        # 103
    upper = chr(code - 32)    # G
    print(code, upper)

Digits, capitals and lower-case letters each have codes in order.

Exam tipA question will usually tell you one code, such as 'A' = 65. Work the others out by counting: you don't need to learn the whole table.
Character code
The number that represents a character, such as 65 for 'A'.
CHAR_TO_CODE / ord()
Converts a character to its character code.
CODE_TO_CHAR / chr()
Converts a character code to its character.
3.2.8 String handling

String conversions

  • You need four conversions: string to integer, string to real, integer to string and real to string.
  • "7" + "8" is the string "78", but 7 + 8 is 15. The data type decides what + does.
  • input() always returns a string, so convert numbers before doing arithmetic with them.
  • int("4.5") stops with an error: the string isn't a whole number. Use float() for it.
  • Python:
    a = "4"
    b = "5"
    print(a + b)              # 45
    print(int(a) + int(b))    # 9
    price = float("2.75")
    print(price * 2)          # 5.5
    label = "Total: " + str(price * 2)
    print(label)              # Total: 5.5
ConversionAQA pseudo-codePythonExample result
String to integerSTRING_TO_INT('16')int("16")16
String to realSTRING_TO_REAL('16.3')float("16.3")16.3
Integer to stringINT_TO_STRING(16)str(16)'16'
Real to stringREAL_TO_STRING(16.3)str(16.3)'16.3'
Exam tipMissing int() or float() round an input() that should be a number counts as an error, so a code answer can't get full marks. Python's name for a real number is float: there is no real().
Casting
Converting a value from one data type to another, such as int("16").
3.2.8 String handling

Looping over strings

  • FOR-IN gives each character in turn: FOR ch IN word in pseudo-code, for ch in word: in Python.
  • Counting characters: start a counter at 0 and add 1 when a character matches. Each comparison needs both sides.
    word = input("Word: ")
    vowels = 0
    for ch in word:
        if ch == "a" or ch == "e" or ch == "i" or ch == "o" or ch == "u":
            vowels = vowels + 1
    print(vowels)
  • Building a new string: start with the empty string and concatenate one character at a time. This reverses a word:
    word ← 'stressed'
    backwards ← ''
    FOR i ← LEN(word) - 1 TO 0 STEP -1
        backwards ← backwards + word[i]
    ENDFOR
    OUTPUT backwards
  • The same in Python:
    word = "stressed"
    backwards = ""
    for i in range(len(word) - 1, -1, -1):
        backwards = backwards + word[i]
    print(backwards)          # desserts
  • String operations are often used to check input, such as its length or its first character. How to write a full validation check is covered in Validation, authentication, testing and errors.
Exam tipif ch == "a" or "e": is always true in Python, because "e" on its own counts as true. Examiners have seen this slip in more than one paper: repeat ch == for each value.
Iterating over a string
Using a loop to take each character of a string in turn.
3.2.9 Random number generation

Random numbers

Programs use random numbers for games, simulations and picking items fairly.

  • AQA pseudo-code: RANDOM_INT(1, 6) gives a random integer from 1 to 6, with both ends included.
  • Python (AQA's form): from random import randrange, then randrange(1, 7). The second number is excluded, so this gives 1 to 6.
  • So for Python, write the second number as one more than the largest value you want.
  • A dice roll:
    from random import randrange
    roll = randrange(1, 7)
    print(roll)
  • AQA's papers may also show import random with random.randrange(1, 7). It does the same thing.
  • Python's randint(1, 6) includes both ends, like RANDOM_INT. It is correct Python, but AQA's papers use randrange, so don't mix the two up.
  • Multiples: 5 * randrange(1, 11) gives 5, 10, 15 … 50.
  • You don't need to know how a computer makes its random numbers.
Values wantedAQA pseudo-codePython
1 to 6RANDOM_INT(1, 6)randrange(1, 7)
0 to 9RANDOM_INT(0, 9)randrange(0, 10)
50 to 100RANDOM_INT(50, 100)randrange(50, 101)

Same values, different second number.

Exam tipIn one AQA paper only half the students got full marks for generating a number from 1 to 100. A common slip was randrange(1, 100), which can never give 100. When a question shows you how to use the random subroutine, copy its format exactly.
Random number generation
The use of algorithms to produce sequences of numbers that appear unpredictable.
RANDOM_INT(a, b)
AQA pseudo-code: a random integer from a to b, both included.
randrange(a, b)
Python: a random integer from a up to b − 1 (b excluded).
3.2.9 Random number generation

Using random numbers in programs

  • Two outcomes (a coin):
    from random import randrange
    flip = randrange(0, 2)
    if flip == 0:
        print("Heads")
    else:
        print("Tails")
  • Picking from an array: generate a random index from 0 to LEN − 1. In pseudo-code: colours[RANDOM_INT(0, LEN(colours) − 1)]. In Python: colours[randrange(0, len(colours))].
  • Simulations: repeat many times and count the results.
    from random import randrange
    sixes = 0
    for throw in range(600):
        if randrange(1, 7) == 6:
            sixes = sixes + 1
    print(sixes)              # about 100, different every run
  • Each call gives a new number. If you need the same number twice (to show it and then check it), store it in a variable first.
  • Generate the number inside the loop if every turn needs a new one, and before the loop if it must stay the same all game.
  • Don't replace the random code with a fixed number to make your answer easier: examiners don't give the marks.
Exam tipIf a game should pick one secret number, put the random line before the loop. Putting it inside the loop changes the secret every turn, which is a logic error.
Random index
A random integer from 0 to LEN − 1, used to pick an element of an array at random.