AQA GCSE Computer Science (8525), section 3.2.8 (String handling operations in a programming language)
Strings
A string is a sequence of characters. In AQA pseudo-code and Python the first character is at position 0.
| Character | H | e | l | l | o |
|---|---|---|---|---|---|
| Position | 0 | 1 | 2 | 3 | 4 |
Operations
| Operation | Pseudo-code | Python | Result for word ← "Hello" |
|---|---|---|---|
| Length | LEN(word) |
len(word) |
5 |
| Position of a character | POSITION(word, "l") |
word.find("l") |
2 |
| Substring (from position 1 to 3) | SUBSTRING(1, 3, word) |
word[1:4] |
"ell" |
| Concatenation (joining) | word + " there" |
word + " there" |
"Hello there" |
| Character to character code | CHAR_TO_CODE("A") |
ord("A") |
65 |
| Character code to character | CODE_TO_CHAR(97) |
chr(97) |
"a" |
Note that in Python the end of a slice is not included, so word[1:4] takes positions 1, 2 and 3. In the AQA pseudo-code both the start and end positions are included.
String conversion operations
| Conversion | Pseudo-code | Python |
|---|---|---|
| string to integer | STRING_TO_INT("42") |
int("42") |
| string to real | STRING_TO_REAL("3.5") |
float("3.5") |
| integer to string | INT_TO_STRING(42) |
str(42) |
| real to string | REAL_TO_STRING(3.5) |
str(3.5) |
Examples in Python
word = "Hello"
print(len(word)) # 5
print(word.find("l")) # 2
print(word[1:4]) # ell
print(word + " there") # Hello there
print(ord("A"), chr(97)) # 65 a
print(int("42") + 1) # 43
print("Score: " + str(12)) # Score: 12
Typical uses
- First letter of a name:
SUBSTRING(0, 0, name). - Make a code: join the first letters of a first name and surname.
- Shift a letter (a Caesar cipher) using character codes.
def shift(letter, key):
return chr((ord(letter) - 65 + key) % 26 + 65)
print(shift("A", 3), shift("Z", 3)) # D C
Common mistake: counting positions from 1. The first character is at position 0. Also, you cannot join a string and a number directly: convert the number to a string first, e.g. "Score " + str(12).
Exam tip: write out the string with the position numbers above each letter before answering a position or substring question. Check whether the end position is included in the version you are using.