String Manipulation
A character code is the number a computer stores to stand for a character, such as its ASCII code. Python gives you two built-in functions for swapping between a character and its code, and they work in opposite directions.
ord() takes a single character and returns its numeric code. chr() takes a code and returns the matching one-character string. Passing more than one character to ord() causes an error, and chr() needs a code that exists in the character set.
| Function | What it does | Type of result |
|---|---|---|
ord() | finds the code for one character | integer |
chr() | finds the character for a code | string |
For example, the capital letter T has code 84, so chr() with 84 gives back T.
Within each case, letter codes go up in alphabetical order, so adding to a code moves you forward through the alphabet until Z. If the code for K is 75, then adding 4 gives 79, which is the code for O, four letters later. The first step finds the starting code with ord(), the arithmetic works out a new code, and chr() turns that code back into a character.
An uppercase letter always has a lower code than the same letter in lowercase, and the gap between the two cases is identical for all 26 letters. Subtracting the code for an uppercase letter from the code for the same lowercase letter always gives that same gap, so subtracting it from a lowercase code gives the uppercase letter and adding it to an uppercase code gives the lowercase letter. For example, adding the gap to the code for W gives the code for w.
start_char = input("Type a capital letter: ")
case_gap = ord('w') - ord('W') # distance from uppercase to lowercase
print("Four along:", chr(ord(start_char) + 4))
print("Lowercase:", chr(ord(start_char) + case_gap))Output when the user types K:
Type a capital letter: K
Four along: O
Lowercase: k OCR GCSE Computer Science · String Manipulation