Try This: Check String Length

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.

Example script: char_access_try_this

  • Enter this script and save it as char_access_try_this.  
  • Flash the script into the micro:bit.
# char_access_try_this

from microbit import *


s = "ABCDEF 12345"
print("Characters in s:")

length = len(s)

print("length =", length)

  • Open the terminal and verify that it displays length = 12.