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.
Example script: char_access_your_turn
- Enter, name, and save char_access_your_turn.
- Click the Send to micro:bit button.
# 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()
- Check the results in the serial monitor.
- Verify that it displays all the characters in the s string along with their ASCII codes.