Some scripts you will write for cybersecurity encryption and decryption will need to access each character in a string. As a warmup for this, let's try a script that checks and displays a certain character in a string.
# char_access_intro from microbit import * sleep(1000) s = "ABCDEF 12345" print("Fifth character in s:") c = s[5] print("c = s[5] =", c) print()
The string s is "ABCDEF 12345". The string name, followed by a positive index value in square brackets, returns the character at that location in the string. The index starts with A at s[0], B is at s[1], and so on up to the character 5 at s[11]. You can also use -1 through -12 to index characters from rightmost to left.
If your script uses an index that's larger than the string, it'll cause an exception. To find out how many characters are in a string, Python has that built-in function called len() that returns the number of characters in a string. Your script can check a string's length, then can then use that result in indexing when accessing characters in that string, so that it never tries to access an out of bounds character. This is especially important when each character is indexed in a loop.
Before indexing all the characters in a string, let's use len() to verify that there are 12 characters in the string.
# char_access_try_this from microbit import * sleep(1000) s = "ABCDEF 12345" print("Characters in s:") length = len(s) print("length =", length) print()
Now that your script can access the length of a string, it can use that number to limit how many characters the script checks in a loop. This makes it possible to access every character safely, without accidentally using an index value that's too large.
This script displays both the individual characters in the string along with their ASCII codes.
# char_access_your_turn from microbit import * sleep(1000) s = "ABCDEF 12345" print("Characters in s:") length = len(s) print("length =", length) print() for n in range(length): c = s[n] a = ord(c) print("s[", n, "] =", c, "| ASCII:", a) print()